xdmf-2.1.dfsg.1/0000755000175000017500000000000011606020330014514 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/0000755000175000017500000000000011606020250016470 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtknetcdf/0000755000175000017500000000000011606020250020460 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtknetcdf/rnd.h0000644000175000017500000000077711606020250021427 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: rnd.h,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #ifndef _RNDUP /* useful for aligning memory */ #define _RNDUP(x, unit) ((((x) + (unit) - 1) / (unit)) \ * (unit)) #define _RNDDOWN(x, unit) ((x) - ((x)%(unit))) #define M_RND_UNIT (sizeof(double)) #define M_RNDUP(x) _RNDUP(x, M_RND_UNIT) #define M_RNDDOWN(x) __RNDDOWN(x, M_RND_UNIT) #endif xdmf-2.1.dfsg.1/Utilities/vtknetcdf/t_nc.c0000644000175000017500000004126011606020250021552 0ustar amckinstryamckinstry/* * Copyright 1988 University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: t_nc.c,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ /* * Program to create a cdf, exercise all cdf functions. * Creates cdf, stuff it full of numbers, closes it. Then * reopens it, and checks for consistency. * Leaves the file around afterwards. * * Based on a program to test the nasa look-alike program, * so not the most appropropriate test. See ../nctest for a * complete spec test. */ #define REDEF /* #define SYNCDEBUG */ #undef NDEBUG /* always active assert() in this file */ #include "ncconfig.h" #include #include #include #include #include #ifdef USE_NETCDF4 #include #include #else #include "netcdf.h" #endif #define MAXSHORT 32767 #define MAXINT 2147483647 #define MAXBYTE 127 #define FNAME "test.nc" #define NUM_DIMS 3 #define DONT_CARE -1 /* make these numbers big when you want to give this a real workout */ #define NUM_RECS 8 #define SIZE_1 7 #define SIZE_2 8 static struct { int num_dims; int num_vars; int num_attrs; int xtendim; } cdesc[1]; static struct { char mnem[NC_MAX_NAME]; nc_type type; int ndims; int dims[NC_MAX_DIMS]; int num_attrs; } vdesc[1]; static struct { char mnem[NC_MAX_NAME]; nc_type type; size_t len; } adesc[1]; union getret { char by[8]; short sh[4]; int in[2]; float fl[2]; double dbl; }; static void chkgot(nc_type type, union getret got, double check) { switch(type){ case NC_BYTE : assert( (char)check == got.by[0] ); break; case NC_CHAR : /* TODO */ assert( (char)check == got.by[0] ); break; case NC_SHORT : assert( (short)check == got.sh[0] ); break; case NC_INT : assert( (int)check == got.in[0] ); break; case NC_FLOAT : assert( (float)check == got.fl[0] ); break; case NC_DOUBLE : assert( check == got.dbl ); break; default: break; } } static const char *fname = FNAME; static size_t num_dims = NUM_DIMS; static size_t sizes[] = { NC_UNLIMITED, SIZE_1 , SIZE_2 }; static const char * const dim_names[] = { "record", "ixx", "iyy"}; static void createtestdims(int cdfid, size_t num_dims, const size_t *sizes, const char * const dim_names[]) { int dimid; while(num_dims-- != 0) { assert( nc_def_dim(cdfid, *dim_names++, *sizes, &dimid) == NC_NOERR); sizes++; } } static void testdims(int cdfid, size_t num_dims, size_t *sizes, const char * const dim_names[]) { int ii; size_t size; char cp[NC_MAX_NAME]; for(ii=0; (size_t) ii < num_dims; ii++, sizes++) { assert( nc_inq_dim(cdfid, ii, cp, &size) == NC_NOERR); if( size != *sizes) (void) fprintf(stderr, "%d: %lu != %lu\n", ii, (unsigned long)size, (unsigned long)*sizes); assert( size == *sizes); assert( strcmp(cp, *dim_names++) == 0); } } static const char * const reqattr[] = { "UNITS", "VALIDMIN", "VALIDMAX", "SCALEMIN", "SCALEMAX", "FIELDNAM", _FillValue }; #define NUM_RATTRS 6 static struct tcdfvar { const char *mnem; nc_type type; const char *fieldnam; double validmin; double validmax; double scalemin; double scalemax; const char *units; int ndims; int dims[NUM_DIMS]; } const testvars[] = { #define Byte_id 0 { "Byte", NC_BYTE, "Byte sized integer variable", -MAXBYTE, MAXBYTE, -MAXBYTE, MAXBYTE , "ones", 2, {0,1,DONT_CARE} }, #define Char_id 1 { "Char", NC_CHAR, "char (string) variable", DONT_CARE, DONT_CARE, DONT_CARE, DONT_CARE, "(unitless)", 2, {0,2,DONT_CARE} }, #define Short_id 2 { "Short", NC_SHORT, "Short variable", -MAXSHORT, MAXSHORT, -MAXSHORT, MAXSHORT , "ones", 2, {0, 2, DONT_CARE }}, #define Long_id 3 { "Long", NC_INT, "Long Integer variable", /* 2.x backward strings */ -MAXINT, MAXINT, -MAXINT, MAXINT, "ones", 2, {1, 2, DONT_CARE}}, #define Float_id 4 { "Float", NC_FLOAT, "Single Precision Floating Point variable", -MAXINT, MAXINT, -MAXINT, MAXINT, "flots", 3, {0, 1, 2 }}, #define Double_id 5 { "Double", NC_DOUBLE, "Double Precision Floating Point variable", -MAXINT, MAXINT, -MAXINT, MAXINT, "dflots", 3, {0, 1, 2 }}, }; #define NUM_TESTVARS 6 static void createtestvars(int id, const struct tcdfvar *testvars, size_t count) { int ii; int varid; const struct tcdfvar *vp = testvars; for(ii = 0; (size_t) ii < count; ii++, vp++ ) { assert(nc_def_var(id, vp->mnem, vp->type, vp->ndims, vp->dims, &varid) == NC_NOERR ); assert( nc_put_att_text(id,ii,reqattr[0],strlen(vp->units), vp->units) == NC_NOERR); assert( nc_put_att_double(id,ii,reqattr[1],NC_DOUBLE,1, &vp->validmin) == NC_NOERR); assert( nc_put_att_double(id,ii,reqattr[2],NC_DOUBLE,1, &vp->validmax) == NC_NOERR); assert( nc_put_att_double(id,ii,reqattr[3],NC_DOUBLE,1, &vp->scalemin) == NC_NOERR); assert( nc_put_att_double(id,ii,reqattr[4],NC_DOUBLE,1, &vp->scalemax) == NC_NOERR); assert( nc_put_att_text(id,ii,reqattr[5],strlen(vp->fieldnam), vp->fieldnam) == NC_NOERR); } } static void parray(const char *label, size_t count, const size_t array[]) { (void) fprintf(stdout, "%s", label); (void) fputc('\t',stdout); for(; count != 0; count--, array++) (void) fprintf(stdout," %lu", (unsigned long) *array); } static void fill_seq(int id) { float values[NUM_RECS * SIZE_1 * SIZE_2]; size_t vindices[NUM_DIMS]; { size_t ii = 0; for(; ii < sizeof(values)/sizeof(values[0]); ii++) { values[ii] = (float) ii; } } /* zero the vindices */ { size_t *cc = vindices; while (cc < &vindices[num_dims]) *cc++ = 0; } sizes[0] = NUM_RECS; assert( nc_put_vara_float(id, Float_id, vindices, sizes, values)== NC_NOERR); } static void check_fill_seq(int id) { size_t vindices[NUM_DIMS]; size_t *cc, *mm; union getret got; int ii = 0; float val; sizes[0] = NUM_RECS; cc = vindices; while (cc < &vindices[num_dims]) *cc++ = 0; /* ripple counter */ cc = vindices; mm = sizes; while (*vindices < *sizes) { while (*cc < *mm) { if (mm == &sizes[num_dims - 1]) { if(nc_get_var1_float(id, Float_id, vindices, &got.fl[0]) == -1) goto bad_ret; val = (float) ii; if(val != got.fl[0]) { parray("indices", NUM_DIMS, vindices); (void) printf("\t%f != %f\n", val, got.fl[0]); } (*cc)++; ii++; continue; } cc++; mm++; } if(cc == vindices) break; *cc = 0; cc--; mm--; (*cc)++; } return; bad_ret : (void) printf("couldn't get a var in check_fill_seq() %d\n", ii); return; } static const size_t indices[][3] = { {0, 1, 3}, {0, 3, 0}, {1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {1, 0, 0}, {0, 0, 0}, }; static const char chs[] = {'A','B', ((char)0xff) }; static const size_t s_start[] = {0,1}; static const size_t s_edges[] = {NUM_RECS, SIZE_1 - 1}; static char sentence[NUM_RECS* SIZE_1 -1] = "The red death had long devastated the country."; static const short shs[] = {97, 99}; static const int birthday = 82555; #define M_E 2.7182818284590452354 static const float e = (float) M_E; static const double pinot = 3.25; static const double zed = 0.0; /*ARGSUSED*/ int main(int ac, char *av[]) { int ret; int id; char buf[256]; #ifdef SYNCDEBUG char *str = "one"; #endif int ii; size_t ui; const struct tcdfvar *tvp = testvars; union getret got; const size_t initialsz = 8192; size_t chunksz = 8192; size_t align = 8192/32; ret = nc__create(fname,NC_NOCLOBBER, initialsz, &chunksz, &id); if(ret != NC_NOERR) { (void) fprintf(stderr, "trying again\n"); ret = nc__create(fname,NC_CLOBBER, initialsz, &chunksz, &id); } if(ret != NC_NOERR) exit(ret); assert( nc_put_att_text(id, NC_GLOBAL, "TITLE", 12, "another name") == NC_NOERR); assert( nc_get_att_text(id, NC_GLOBAL, "TITLE", buf) == NC_NOERR); /* (void) printf("title 1 \"%s\"\n", buf); */ assert( nc_put_att_text(id, NC_GLOBAL, "TITLE", strlen(fname), fname) == NC_NOERR); assert( nc_get_att_text(id, NC_GLOBAL, "TITLE", buf) == NC_NOERR); buf[strlen(fname)] = 0; /* (void) printf("title 2 \"%s\"\n", buf); */ assert( strcmp(fname, buf) == 0); createtestdims(id, NUM_DIMS, sizes, dim_names); testdims(id, NUM_DIMS, sizes, dim_names); createtestvars(id, testvars, NUM_TESTVARS); { int ifill = -1; double dfill = -9999; assert( nc_put_att_int(id, Long_id, _FillValue, NC_INT, 1, &ifill) == NC_NOERR); assert( nc_put_att_double(id, Double_id, _FillValue, NC_DOUBLE, 1, &dfill) == NC_NOERR); } #ifdef REDEF assert( nc__enddef(id, 0, align, 0, 2*align) == NC_NOERR ); assert( nc_put_var1_int(id, Long_id, indices[3], &birthday) == NC_NOERR ); fill_seq(id); assert( nc_redef(id) == NC_NOERR ); /* assert( nc_rename_dim(id,2, "a long dim name") == NC_NOERR); */ #endif assert( nc_rename_dim(id,1, "IXX") == NC_NOERR); assert( nc_inq_dim(id, 1, buf, &ui) == NC_NOERR); (void) printf("dimrename: %s\n", buf); assert( nc_rename_dim(id,1, dim_names[1]) == NC_NOERR); #ifdef ATTRX assert( nc_rename_att(id, 1, "UNITS", "units") == NC_NOERR); assert( nc_del_att(id, 4, "FIELDNAM")== NC_NOERR); assert( nc_del_att(id, 2, "SCALEMIN")== NC_NOERR); assert( nc_del_att(id, 2, "SCALEMAX")== NC_NOERR); #endif /* ATTRX */ assert( nc__enddef(id, 0, align, 0, 2*align) == NC_NOERR ); #ifndef REDEF fill_seq(id); assert( nc_put_var1_int(id, Long_id, indices[3], &birthday)== NC_NOERR ); #endif assert( nc_put_vara_schar(id, Byte_id, s_start, s_edges, (signed char *)sentence) == NC_NOERR); assert( nc_put_var1_schar(id, Byte_id, indices[6], (signed char *)(chs+1)) == NC_NOERR); assert( nc_put_var1_schar(id, Byte_id, indices[5], (signed char *)chs) == NC_NOERR); assert( nc_put_vara_text(id, Char_id, s_start, s_edges, sentence) == NC_NOERR); assert( nc_put_var1_text(id, Char_id, indices[6], (chs+1)) == NC_NOERR) ; assert( nc_put_var1_text(id, Char_id, indices[5], chs) == NC_NOERR); assert( nc_put_var1_short(id, Short_id, indices[4], shs) == NC_NOERR); assert( nc_put_var1_float(id, Float_id, indices[2], &e) == NC_NOERR); assert( nc_put_var1_double(id, Double_id, indices[1], &zed) == NC_NOERR); assert( nc_put_var1_double(id, Double_id, indices[0], &pinot) == NC_NOERR); #ifdef SYNCDEBUG (void) printf("Hit Return to sync\n"); gets(str); nc_sync(id,0); (void) printf("Sync done. Hit Return to continue\n"); gets(str); #endif /* SYNCDEBUG */ ret = nc_close(id); (void) printf("nc_close ret = %d\n\n", ret); /* * read it */ ret = nc__open(fname,NC_NOWRITE, &chunksz, &id); if(ret != NC_NOERR) { (void) printf("Could not open %s: %s\n", fname, nc_strerror(ret)); exit(1); } (void) printf("reopen id = %d for filename %s\n", id, fname); /* NC */ (void) printf("NC "); assert( nc_inq(id, &(cdesc->num_dims), &(cdesc->num_vars), &(cdesc->num_attrs), &(cdesc->xtendim) ) == NC_NOERR); assert((size_t) cdesc->num_dims == num_dims); assert(cdesc->num_attrs == 1); assert(cdesc->num_vars == NUM_TESTVARS); (void) printf("done\n"); /* GATTR */ (void) printf("GATTR "); assert( nc_inq_attname(id, NC_GLOBAL, 0, adesc->mnem) == 0); assert(strcmp("TITLE",adesc->mnem) == 0); assert( nc_inq_att(id, NC_GLOBAL, adesc->mnem, &(adesc->type), &(adesc->len))== NC_NOERR); assert( adesc->type == NC_CHAR ); assert( adesc->len == strlen(fname) ); assert( nc_get_att_text(id, NC_GLOBAL, "TITLE", buf)== NC_NOERR); buf[adesc->len] = 0; assert( strcmp(fname, buf) == 0); /* VAR */ (void) printf("VAR "); assert( cdesc->num_vars == NUM_TESTVARS ); for(ii = 0; ii < cdesc->num_vars; ii++, tvp++ ) { int jj; assert( nc_inq_var(id, ii, vdesc->mnem, &(vdesc->type), &(vdesc->ndims), vdesc->dims, &(vdesc->num_attrs)) == NC_NOERR); if(strcmp(tvp->mnem , vdesc->mnem) != 0) { (void) printf("attr %d mnem mismatch %s, %s\n", ii, tvp->mnem, vdesc->mnem); continue; } if(tvp->type != vdesc->type) { (void) printf("attr %d type mismatch %d, %d\n", ii, (int)tvp->type, (int)vdesc->type); continue; } for(jj = 0; jj < vdesc->ndims; jj++ ) { if(tvp->dims[jj] != vdesc->dims[jj] ) { (void) printf( "inconsistent dim[%d] for variable %d: %d != %d\n", jj, ii, tvp->dims[jj], vdesc->dims[jj] ); continue; } } /* VATTR */ (void) printf("VATTR\n"); for(jj=0; jjnum_attrs; jj++ ) { assert( nc_inq_attname(id, ii, jj, adesc->mnem) == NC_NOERR); if( strcmp(adesc->mnem, reqattr[jj]) != 0 ) { (void) printf("var %d attr %d mismatch %s != %s\n", ii, jj, adesc->mnem, reqattr[jj] ); break; } } if( nc_inq_att(id, ii, reqattr[0], &(adesc->type), &(adesc->len)) != -1) { assert( adesc->type == NC_CHAR ); assert( adesc->len == strlen(tvp->units) ); assert( nc_get_att_text(id,ii,reqattr[0],buf)== NC_NOERR); buf[adesc->len] = 0; assert( strcmp(tvp->units, buf) == 0); } if( nc_inq_att(id, ii, reqattr[1], &(adesc->type), &(adesc->len)) != -1) { assert( adesc->type == NC_DOUBLE ); assert( adesc->len == 1 ); assert( nc_get_att_double(id, ii, reqattr[1], &got.dbl)== NC_NOERR); chkgot(adesc->type, got, tvp->validmin); } if( nc_inq_att(id, ii, reqattr[2], &(adesc->type), &(adesc->len)) != -1) { assert( adesc->type == NC_DOUBLE ); assert( adesc->len == 1 ); assert( nc_get_att_double(id, ii, reqattr[2], &got.dbl)== NC_NOERR); chkgot(adesc->type, got, tvp->validmax); } if( nc_inq_att(id, ii, reqattr[3], &(adesc->type), &(adesc->len)) != -1) { assert( adesc->type == NC_DOUBLE ); assert( adesc->len ==1 ); assert( nc_get_att_double(id, ii, reqattr[3], &got.dbl)== NC_NOERR); chkgot(adesc->type, got, tvp->scalemin); } if( nc_inq_att(id, ii, reqattr[4], &(adesc->type), &(adesc->len)) != -1) { assert( adesc->type == NC_DOUBLE ); assert( adesc->len == 1 ); assert( nc_get_att_double(id, ii, reqattr[4], &got.dbl)== NC_NOERR); chkgot(adesc->type, got, tvp->scalemax); } if( nc_inq_att(id, ii, reqattr[5], &(adesc->type), &(adesc->len))== NC_NOERR) { assert( adesc->type == NC_CHAR ); assert( adesc->len == strlen(tvp->fieldnam) ); assert( nc_get_att_text(id,ii,reqattr[5],buf)== NC_NOERR); buf[adesc->len] = 0; assert( strcmp(tvp->fieldnam, buf) == 0); } } (void) printf("fill_seq "); check_fill_seq(id); (void) printf("Done\n"); assert( nc_get_var1_double(id, Double_id, indices[0], &got.dbl)== NC_NOERR); (void) printf("got val = %f\n", got.dbl ); assert( nc_get_var1_double(id, Double_id, indices[1], &got.dbl)== NC_NOERR); (void) printf("got val = %f\n", got.dbl ); assert( nc_get_var1_float(id, Float_id, indices[2], &got.fl[0])== NC_NOERR); (void) printf("got val = %f\n", got.fl[0] ); assert( nc_get_var1_int(id, Long_id, indices[3], &got.in[0])== NC_NOERR); (void) printf("got val = %d\n", got.in[0] ); assert( nc_get_var1_short(id, Short_id, indices[4], &got.sh[0])== NC_NOERR); (void) printf("got val = %d\n", got.sh[0] ); assert( nc_get_var1_text(id, Char_id, indices[5], &got.by[0]) == NC_NOERR); (void) printf("got NC_CHAR val = %c (0x%02x) \n", got.by[0] , got.by[0]); assert( nc_get_var1_text(id, Char_id, indices[6], &got.by[0]) == NC_NOERR); (void) printf("got NC_CHAR val = %c (0x%02x) \n", got.by[0], got.by[0] ); (void) memset(buf,0,sizeof(buf)); assert( nc_get_vara_text(id, Char_id, s_start, s_edges, buf) == NC_NOERR); (void) printf("got NC_CHAR val = \"%s\"\n", buf); assert( nc_get_var1_schar(id, Byte_id, indices[5], (signed char *)&got.by[0])== NC_NOERR); (void) printf("got val = %c (0x%02x) \n", got.by[0] , got.by[0]); assert( nc_get_var1_schar(id, Byte_id, indices[6], (signed char *)&got.by[0])== NC_NOERR); (void) printf("got val = %c (0x%02x) \n", got.by[0], got.by[0] ); (void) memset(buf,0,sizeof(buf)); assert( nc_get_vara_schar(id, Byte_id, s_start, s_edges, (signed char *)buf)== NC_NOERR ); (void) printf("got val = \"%s\"\n", buf); { double dbuf[NUM_RECS * SIZE_1 * SIZE_2]; assert(nc_get_var_double(id, Float_id, dbuf) == NC_NOERR); (void) printf("got vals = %f ... %f\n", dbuf[0], dbuf[NUM_RECS * SIZE_1 * SIZE_2 -1] ); } ret = nc_close(id); (void) printf("re nc_close ret = %d\n", ret); return 0; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/nc.c0000644000175000017500000010262711606020250021234 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: nc.c,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #include "nc.h" #include "rnd.h" #include #include #include #include "ncx.h" #if defined(LOCKNUMREC) /* && _CRAYMPP */ # include # include #endif #ifdef __BORLANDC__ # pragma warn -8004 /* "assigned a value that is never used" */ # pragma warn -8065 /* "Call to function 'XXX' with no prototype" */ #endif #if defined(_MSC_VER) && (_MSC_VER >= 1300) # pragma warning ( disable : 4127 ) /* conditional expression is constant */ # pragma warning ( disable : 4130 ) /* logical operation on address of string constant */ #endif /* MSVC 7.1 */ /* list of open netcdf's */ static NC *NClist = NULL; /* This is the default create format for nc_create and nc__create. */ int default_create_format = NC_FORMAT_CLASSIC; /* These have to do with version numbers. */ #define MAGIC_NUM_LEN 4 #define VER_CLASSIC 1 #define VER_64BIT_OFFSET 2 #define VER_HDF5 3 static void add_to_NCList(NC *ncp) { assert(ncp != NULL); ncp->prev = NULL; if(NClist != NULL) NClist->prev = ncp; ncp->next = NClist; NClist = ncp; } static void del_from_NCList(NC *ncp) { assert(ncp != NULL); if(NClist == ncp) { assert(ncp->prev == NULL); NClist = ncp->next; } else { assert(ncp->prev != NULL); ncp->prev->next = ncp->next; } if(ncp->next != NULL) ncp->next->prev = ncp->prev; ncp->next = NULL; ncp->prev = NULL; } int NC_check_id(int ncid, NC **ncpp) { NC *ncp; if(ncid >= 0) { for(ncp = NClist; ncp != NULL; ncp = ncp->next) { if(ncp->nciop->fd == ncid) { *ncpp = ncp; return NC_NOERR; /* normal return */ } } } /* else, not found */ return NC_EBADID; } static void free_NC(NC *ncp) { if(ncp == NULL) return; free_NC_dimarrayV(&ncp->dims); free_NC_attrarrayV(&ncp->attrs); free_NC_vararrayV(&ncp->vars); #if _CRAYMPP && defined(LOCKNUMREC) shfree(ncp); #else free(ncp); #endif /* _CRAYMPP && LOCKNUMREC */ } static NC * new_NC(const size_t *chunkp) { NC *ncp; #if _CRAYMPP && defined(LOCKNUMREC) ncp = (NC *) shmalloc(sizeof(NC)); #else ncp = (NC *) malloc(sizeof(NC)); #endif /* _CRAYMPP && LOCKNUMREC */ if(ncp == NULL) return NULL; (void) memset(ncp, 0, sizeof(NC)); ncp->xsz = MIN_NC_XSZ; assert(ncp->xsz == ncx_len_NC(ncp,0)); ncp->chunk = chunkp != NULL ? *chunkp : NC_SIZEHINT_DEFAULT; return ncp; } static NC * dup_NC(const NC *ref) { NC *ncp; #if _CRAYMPP && defined(LOCKNUMREC) ncp = (NC *) shmalloc(sizeof(NC)); #else ncp = (NC *) malloc(sizeof(NC)); #endif /* _CRAYMPP && LOCKNUMREC */ if(ncp == NULL) return NULL; (void) memset(ncp, 0, sizeof(NC)); if(dup_NC_dimarrayV(&ncp->dims, &ref->dims) != NC_NOERR) goto err; if(dup_NC_attrarrayV(&ncp->attrs, &ref->attrs) != NC_NOERR) goto err; if(dup_NC_vararrayV(&ncp->vars, &ref->vars) != NC_NOERR) goto err; ncp->xsz = ref->xsz; ncp->begin_var = ref->begin_var; ncp->begin_rec = ref->begin_rec; ncp->recsize = ref->recsize; NC_set_numrecs(ncp, NC_get_numrecs(ref)); return ncp; err: free_NC(ncp); return NULL; } /* * Verify that this is a user nc_type * Formerly NCcktype() * Sense of the return is changed. */ int nc_cktype(nc_type type) { switch((int)type){ case NC_BYTE: case NC_CHAR: case NC_SHORT: case NC_INT: case NC_FLOAT: case NC_DOUBLE: return(NC_NOERR); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return(NC_EBADTYPE); } /* * How many objects of 'type' * will fit into xbufsize? */ size_t ncx_howmany(nc_type type, size_t xbufsize) { switch(type){ case NC_BYTE: case NC_CHAR: return xbufsize; case NC_SHORT: return xbufsize/X_SIZEOF_SHORT; case NC_INT: return xbufsize/X_SIZEOF_INT; case NC_FLOAT: return xbufsize/X_SIZEOF_FLOAT; case NC_DOUBLE: return xbufsize/X_SIZEOF_DOUBLE; case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_howmany: Bad type" == 0); return(0); } #define D_RNDUP(x, align) _RNDUP(x, (off_t)(align)) /* * Compute each variable's 'begin' offset, * update 'begin_rec' as well. */ static int NC_begins(NC *ncp, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align) { size_t ii; int sizeof_off_t; off_t index2; NC_var **vpp; NC_var *last = NULL; if(v_align == NC_ALIGN_CHUNK) v_align = ncp->chunk; if(r_align == NC_ALIGN_CHUNK) r_align = ncp->chunk; if (fIsSet(ncp->flags, NC_64BIT_OFFSET)) { sizeof_off_t = 8; } else { sizeof_off_t = 4; } ncp->xsz = ncx_len_NC(ncp,sizeof_off_t); if(ncp->vars.nelems == 0) return NC_NOERR; /* only (re)calculate begin_var if there is not sufficient space in header or start of non-record variables is not aligned as requested by valign */ if ((size_t)ncp->begin_var < ncp->xsz + h_minfree || ncp->begin_var != D_RNDUP(ncp->begin_var, v_align) ) { index2 = (off_t) ncp->xsz; ncp->begin_var = D_RNDUP(index2, v_align); if(ncp->begin_var < index2 + (off_t)h_minfree) { ncp->begin_var = D_RNDUP(index2 + (off_t)h_minfree, v_align); } } index2 = ncp->begin_var; /* loop thru vars, first pass is for the 'non-record' vars */ vpp = ncp->vars.value; for(ii = 0; ii < ncp->vars.nelems ; ii++, vpp++) { if( IS_RECVAR(*vpp) ) { /* skip record variables on this pass */ continue; } #if 0 fprintf(stderr, " VAR %d %s: %ld\n", ii, (*vpp)->name->cp, (long)index2); #endif if( sizeof_off_t == 4 && (index2 > X_OFF_MAX || index2 < 0) ) { return NC_EVARSIZE; } (*vpp)->begin = index2; index2 += (*vpp)->len; } /* only (re)calculate begin_rec if there is not sufficient space at end of non-record variables or if start of record variables is not aligned as requested by r_align */ if (ncp->begin_rec < index2 + (off_t)v_minfree || ncp->begin_rec != D_RNDUP(ncp->begin_rec, r_align) ) { ncp->begin_rec = D_RNDUP(index2, r_align); if(ncp->begin_rec < index2 + (off_t)v_minfree) { ncp->begin_rec = D_RNDUP(index2 + (off_t)v_minfree, r_align); } } index2 = ncp->begin_rec; ncp->recsize = 0; /* loop thru vars, second pass is for the 'record' vars */ vpp = (NC_var **)ncp->vars.value; for(ii = 0; ii < ncp->vars.nelems; ii++, vpp++) { if( !IS_RECVAR(*vpp) ) { /* skip non-record variables on this pass */ continue; } #if 0 fprintf(stderr, " REC %d %s: %ld\n", ii, (*vpp)->name->cp, (long)index2); #endif if( sizeof_off_t == 4 && (index2 > X_OFF_MAX || index2 < 0) ) { return NC_EVARSIZE; } (*vpp)->begin = index2; index2 += (*vpp)->len; /* check if record size must fit in 32-bits */ #if SIZEOF_OFF_T == SIZEOF_SIZE_T && SIZEOF_SIZE_T == 4 if( ncp->recsize > X_UINT_MAX - (*vpp)->len ) { return NC_EVARSIZE; } #endif ncp->recsize += (*vpp)->len; last = (*vpp); } /* * for special case of exactly one record variable, pack value */ if(last != NULL && ncp->recsize == last->len) ncp->recsize = *last->dsizes * last->xsz; if(NC_IsNew(ncp)) NC_set_numrecs(ncp, 0); return NC_NOERR; } /* * Read just the numrecs member. * (A relatively expensive way to do things.) */ int read_numrecs(NC *ncp) { int status; const void *xp = NULL; size_t nrecs = NC_get_numrecs(ncp); assert(!NC_indef(ncp)); #define NC_NUMRECS_OFFSET 4 #define NC_NUMRECS_EXTENT 4 status = ncp->nciop->get(ncp->nciop, NC_NUMRECS_OFFSET, NC_NUMRECS_EXTENT, 0, (void **)&xp); /* cast away const */ if(status != NC_NOERR) return status; status = ncx_get_size_t(&xp, &nrecs); (void) ncp->nciop->rel(ncp->nciop, NC_NUMRECS_OFFSET, 0); if(status == NC_NOERR) { NC_set_numrecs(ncp, nrecs); fClr(ncp->flags, NC_NDIRTY); } return status; } /* * Write out just the numrecs member. * (A relatively expensive way to do things.) */ int write_numrecs(NC *ncp) { int status; void *xp = NULL; assert(!NC_readonly(ncp)); assert(!NC_indef(ncp)); status = ncp->nciop->get(ncp->nciop, NC_NUMRECS_OFFSET, NC_NUMRECS_EXTENT, RGN_WRITE, &xp); if(status != NC_NOERR) return status; { const size_t nrecs = NC_get_numrecs(ncp); status = ncx_put_size_t(&xp, &nrecs); } (void) ncp->nciop->rel(ncp->nciop, NC_NUMRECS_OFFSET, RGN_MODIFIED); if(status == NC_NOERR) fClr(ncp->flags, NC_NDIRTY); return status; } /* * Read in the header * It is expensive. */ static int read_NC(NC *ncp) { int status; free_NC_dimarrayV(&ncp->dims); free_NC_attrarrayV(&ncp->attrs); free_NC_vararrayV(&ncp->vars); status = nc_get_NC(ncp); if(status == NC_NOERR) fClr(ncp->flags, NC_NDIRTY | NC_HDIRTY); return status; } /* * Write out the header */ static int write_NC(NC *ncp) { int status; assert(!NC_readonly(ncp)); status = ncx_put_NC(ncp, NULL, 0, 0); if(status == NC_NOERR) fClr(ncp->flags, NC_NDIRTY | NC_HDIRTY); return status; } /* * Write the header or the numrecs if necessary. */ int NC_sync(NC *ncp) { assert(!NC_readonly(ncp)); if(NC_hdirty(ncp)) { return write_NC(ncp); } /* else */ if(NC_ndirty(ncp)) { return write_numrecs(ncp); } /* else */ return NC_NOERR; } /* * Initialize the 'non-record' variables. */ static int fillerup(NC *ncp) { int status = NC_NOERR; size_t ii; NC_var **varpp; assert(!NC_readonly(ncp)); assert(NC_dofill(ncp)); /* loop thru vars */ varpp = ncp->vars.value; for(ii = 0; ii < ncp->vars.nelems; ii++, varpp++) { if(IS_RECVAR(*varpp)) { /* skip record variables */ continue; } status = fill_NC_var(ncp, *varpp, (*varpp)->len, 0); if(status != NC_NOERR) break; } return status; } /* Begin endef */ /* */ static int fill_added_recs(NC *gnu, NC *old) { NC_var ** const gnu_varpp = (NC_var **)gnu->vars.value; /* NC_var *const *const gnu_end = &gnu_varpp[gnu->vars.nelems]; */ const int old_nrecs = (int) NC_get_numrecs(old); int recno = 0; NC_var **vpp = gnu_varpp; NC_var *const *const end = &vpp[gnu->vars.nelems]; int numrecvars = 0; NC_var *recvarp; /* Determine if there is only one record variable. If so, we must treat as a special case because there's no record padding */ for(; vpp < end; vpp++) { if(IS_RECVAR(*vpp)) { recvarp = *vpp; numrecvars++; } } for(; recno < old_nrecs; recno++) { int varid = (int)old->vars.nelems; for(; varid < (int)gnu->vars.nelems; varid++) { const NC_var *const gnu_varp = *(gnu_varpp + varid); if(!IS_RECVAR(gnu_varp)) { /* skip non-record variables */ continue; } /* else */ { size_t varsize = numrecvars == 1 ? gnu->recsize : gnu_varp->len; const int status = fill_NC_var(gnu, gnu_varp, varsize, recno); if(status != NC_NOERR) return status; } } } return NC_NOERR; } /* */ static int fill_added(NC *gnu, NC *old) { NC_var ** const gnu_varpp = (NC_var **)gnu->vars.value; int varid = (int)old->vars.nelems; for(; varid < (int)gnu->vars.nelems; varid++) { const NC_var *const gnu_varp = *(gnu_varpp + varid); if(IS_RECVAR(gnu_varp)) { /* skip record variables */ continue; } /* else */ { const int status = fill_NC_var(gnu, gnu_varp, gnu_varp->len, 0); if(status != NC_NOERR) return status; } } return NC_NOERR; } /* * Move the records "out". * Fill as needed. */ static int move_recs_r(NC *gnu, NC *old) { int status; int recno; int varid; NC_var **gnu_varpp = (NC_var **)gnu->vars.value; NC_var **old_varpp = (NC_var **)old->vars.value; NC_var *gnu_varp; NC_var *old_varp; off_t gnu_off; off_t old_off; const size_t old_nrecs = NC_get_numrecs(old); /* Don't parallelize this loop */ for(recno = (int)old_nrecs -1; recno >= 0; recno--) { /* Don't parallelize this loop */ for(varid = (int)old->vars.nelems -1; varid >= 0; varid--) { gnu_varp = *(gnu_varpp + varid); if(!IS_RECVAR(gnu_varp)) { /* skip non-record variables on this pass */ continue; } /* else */ /* else, a pre-existing variable */ old_varp = *(old_varpp + varid); gnu_off = gnu_varp->begin + (off_t)(gnu->recsize * recno); old_off = old_varp->begin + (off_t)(old->recsize * recno); if(gnu_off == old_off) continue; /* nothing to do */ assert(gnu_off > old_off); status = gnu->nciop->move(gnu->nciop, gnu_off, old_off, old_varp->len, 0); if(status != NC_NOERR) return status; } } NC_set_numrecs(gnu, old_nrecs); return NC_NOERR; } /* * Move the "non record" variables "out". * Fill as needed. */ static int move_vars_r(NC *gnu, NC *old) { int status; int varid; NC_var **gnu_varpp = (NC_var **)gnu->vars.value; NC_var **old_varpp = (NC_var **)old->vars.value; NC_var *gnu_varp; NC_var *old_varp; off_t gnu_off; off_t old_off; /* Don't parallelize this loop */ for(varid = (int)old->vars.nelems -1; varid >= 0; varid--) { gnu_varp = *(gnu_varpp + varid); if(IS_RECVAR(gnu_varp)) { /* skip record variables on this pass */ continue; } /* else */ old_varp = *(old_varpp + varid); gnu_off = gnu_varp->begin; old_off = old_varp->begin; if(gnu_off == old_off) continue; /* nothing to do */ assert(gnu_off > old_off); status = gnu->nciop->move(gnu->nciop, gnu_off, old_off, old_varp->len, 0); if(status != NC_NOERR) return status; } return NC_NOERR; } /* * Given a valid ncp, return NC_EVARSIZE if any variable has a bad len * (product of non-rec dim sizes too large), else return NC_NOERR. */ static int NC_check_vlens(NC *ncp) { NC_var **vpp; /* maximum permitted variable size (or size of one record's worth of a record variable) in bytes. This is different for format 1 and format 2. */ size_t vlen_max; size_t ii; size_t large_vars_count; size_t rec_vars_count; int last = 0; if(ncp->vars.nelems == 0) return NC_NOERR; if ((ncp->flags & NC_64BIT_OFFSET) && sizeof(off_t) > 4) { /* CDF2 format and LFS */ vlen_max = X_UINT_MAX - 3; /* "- 3" handles rounded-up size */ } else { /* CDF1 format */ vlen_max = X_INT_MAX - 3; } /* Loop through vars, first pass is for non-record variables. */ large_vars_count = 0; rec_vars_count = 0; vpp = ncp->vars.value; for (ii = 0; ii < ncp->vars.nelems; ii++, vpp++) { if( !IS_RECVAR(*vpp) ) { last = 0; if( NC_check_vlen(*vpp, vlen_max) == 0 ) { large_vars_count++; last = 1; } } else { rec_vars_count++; } } /* OK if last non-record variable size too large, since not used to compute an offset */ if( large_vars_count > 1) { /* only one "too-large" variable allowed */ return NC_EVARSIZE; } /* and it has to be the last one */ if( large_vars_count == 1 && last == 0) { return NC_EVARSIZE; } if( rec_vars_count > 0 ) { /* and if it's the last one, there can't be any record variables */ if( large_vars_count == 1 && last == 1) { return NC_EVARSIZE; } /* Loop through vars, second pass is for record variables. */ large_vars_count = 0; vpp = ncp->vars.value; for (ii = 0; ii < ncp->vars.nelems; ii++, vpp++) { if( IS_RECVAR(*vpp) ) { last = 0; if( NC_check_vlen(*vpp, vlen_max) == 0 ) { large_vars_count++; last = 1; } } } /* OK if last record variable size too large, since not used to compute an offset */ if( large_vars_count > 1) { /* only one "too-large" variable allowed */ return NC_EVARSIZE; } /* and it has to be the last one */ if( large_vars_count == 1 && last == 0) { return NC_EVARSIZE; } } return NC_NOERR; } /* * End define mode. * Common code for ncendef, ncclose(endef) * Flushes I/O buffers. */ static int NC_endef(NC *ncp, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align) { int status; assert(!NC_readonly(ncp)); assert(NC_indef(ncp)); status = NC_check_vlens(ncp); if(status != NC_NOERR) return status; status = NC_begins(ncp, h_minfree, v_align, v_minfree, r_align); if(status != NC_NOERR) return status; if(ncp->old != NULL) { /* a plain redef, not a create */ assert(!NC_IsNew(ncp)); assert(fIsSet(ncp->flags, NC_INDEF)); assert(ncp->begin_rec >= ncp->old->begin_rec); assert(ncp->begin_var >= ncp->old->begin_var); if(ncp->vars.nelems != 0) { if(ncp->begin_rec > ncp->old->begin_rec) { status = move_recs_r(ncp, ncp->old); if(status != NC_NOERR) return status; if(ncp->begin_var > ncp->old->begin_var) { status = move_vars_r(ncp, ncp->old); if(status != NC_NOERR) return status; } /* else if (ncp->begin_var == ncp->old->begin_var) { NOOP } */ } else { /* Even if (ncp->begin_rec == ncp->old->begin_rec) and (ncp->begin_var == ncp->old->begin_var) might still have added a new record variable */ if(ncp->recsize > ncp->old->recsize) { status = move_recs_r(ncp, ncp->old); if(status != NC_NOERR) return status; } } } } status = write_NC(ncp); if(status != NC_NOERR) return status; if(NC_dofill(ncp)) { if(NC_IsNew(ncp)) { status = fillerup(ncp); if(status != NC_NOERR) return status; } else if(ncp->vars.nelems > ncp->old->vars.nelems) { status = fill_added(ncp, ncp->old); if(status != NC_NOERR) return status; status = fill_added_recs(ncp, ncp->old); if(status != NC_NOERR) return status; } } if(ncp->old != NULL) { free_NC(ncp->old); ncp->old = NULL; } fClr(ncp->flags, NC_CREAT | NC_INDEF); return ncp->nciop->sync(ncp->nciop); } #ifdef LOCKNUMREC static int NC_init_pe(NC *ncp, int basepe) { if (basepe < 0 || basepe >= _num_pes()) { return NC_EINVAL; /* invalid base pe */ } /* initialize common values */ ncp->lock[LOCKNUMREC_VALUE] = 0; ncp->lock[LOCKNUMREC_LOCK] = 0; ncp->lock[LOCKNUMREC_SERVING] = 0; ncp->lock[LOCKNUMREC_BASEPE] = basepe; return NC_NOERR; } #endif /* * Compute the expected size of the file. */ int NC_calcsize(NC *ncp, off_t *calcsizep) { NC_var **vpp = (NC_var **)ncp->vars.value; NC_var *const *const end = &vpp[ncp->vars.nelems]; NC_var *last_fix = NULL; /* last "non-record" var */ NC_var *last_rec; /* last "record" var */ /*NC_var *last_var;*/ int status; int numrecvars = 0; /* number of record variables */ if(ncp->vars.nelems == 0) { /* no non-record variables and no record variables */ *calcsizep = ncp->xsz; /* size of header */ return NC_NOERR; } for( /*NADA*/; vpp < end; vpp++) { status = NC_var_shape(*vpp, &ncp->dims); if(status != NC_NOERR) return status; if(IS_RECVAR(*vpp)) { last_rec = *vpp; numrecvars++; } else { last_fix = *vpp; } } if(numrecvars == 0) { assert(last_fix != NULL); *calcsizep = last_fix->begin + last_fix->len; /*last_var = last_fix;*/ } else { /* we have at least one record variable */ *calcsizep = ncp->begin_rec + ncp->numrecs * ncp->recsize; /*last_var = last_rec;*/ } return NC_NOERR; } /* Public */ int nc__create(const char * path, int ioflags, size_t initialsz, size_t *chunksizehintp, int *ncid_ptr) { return nc__create_mp(path, ioflags, initialsz, 0, chunksizehintp, ncid_ptr); } int nc__create_mp(const char * path, int ioflags, size_t initialsz, int basepe, size_t *chunksizehintp, int *ncid_ptr) { NC *ncp; int status; void *xp = NULL; int sizeof_off_t; #if ALWAYS_NC_SHARE /* DEBUG */ fSet(ioflags, NC_SHARE); #endif ncp = new_NC(chunksizehintp); if(ncp == NULL) return NC_ENOMEM; #if defined(LOCKNUMREC) /* && _CRAYMPP */ if (status = NC_init_pe(ncp, basepe)) { return status; } #else /* * !_CRAYMPP, only pe 0 is valid */ if(basepe != 0) return NC_EINVAL; #endif assert(ncp->flags == 0); /* Apply default create format. */ if (default_create_format == NC_FORMAT_64BIT) ioflags |= NC_64BIT_OFFSET; if (fIsSet(ioflags, NC_64BIT_OFFSET)) { fSet(ncp->flags, NC_64BIT_OFFSET); sizeof_off_t = 8; } else { sizeof_off_t = 4; } assert(ncp->xsz == ncx_len_NC(ncp,sizeof_off_t)); status = ncio_create(path, ioflags, initialsz, 0, ncp->xsz, &ncp->chunk, &ncp->nciop, &xp); if(status != NC_NOERR) { /* translate error status */ if(status == EEXIST) status = NC_EEXIST; goto unwind_alloc; } fSet(ncp->flags, NC_CREAT); if(fIsSet(ncp->nciop->ioflags, NC_SHARE)) { /* * NC_SHARE implies sync up the number of records as well. * (File format version one.) * Note that other header changes are not shared * automatically. Some sort of IPC (external to this package) * would be used to trigger a call to nc_sync(). */ fSet(ncp->flags, NC_NSYNC); } status = ncx_put_NC(ncp, &xp, sizeof_off_t, ncp->xsz); if(status != NC_NOERR) goto unwind_ioc; add_to_NCList(ncp); if(chunksizehintp != NULL) *chunksizehintp = ncp->chunk; *ncid_ptr = ncp->nciop->fd; return NC_NOERR; unwind_ioc: (void) ncio_close(ncp->nciop, 1); /* N.B.: unlink */ ncp->nciop = NULL; /*FALLTHRU*/ unwind_alloc: free_NC(ncp); return status; } /* This function sets a default create flag that will be logically or'd to whatever flags are passed into nc_create for all future calls to nc_create. Valid default create flags are NC_64BIT_OFFSET, NC_CLOBBER, NC_LOCK, NC_SHARE. */ int nc_set_default_format(int format, int *old_formatp) { /* Return existing format if desired. */ if (old_formatp) *old_formatp = default_create_format; /* Make sure only valid format is set. */ #ifdef USE_NETCDF4 if (format != NC_FORMAT_CLASSIC && format != NC_FORMAT_64BIT && format != NC_FORMAT_NETCDF4 && format != NC_FORMAT_NETCDF4_CLASSIC) return NC_EINVAL; #else if (format != NC_FORMAT_CLASSIC && format != NC_FORMAT_64BIT) return NC_EINVAL; #endif default_create_format = format; return NC_NOERR; } int nc_create(const char * path, int ioflags, int *ncid_ptr) { return nc__create(path, ioflags, 0, NULL, ncid_ptr); } int nc__open(const char * path, int ioflags, size_t *chunksizehintp, int *ncid_ptr) { return nc__open_mp(path, ioflags, 0, chunksizehintp, ncid_ptr); } int nc__open_mp(const char * path, int ioflags, int basepe, size_t *chunksizehintp, int *ncid_ptr) { NC *ncp; int status; #if ALWAYS_NC_SHARE /* DEBUG */ fSet(ioflags, NC_SHARE); #endif ncp = new_NC(chunksizehintp); if(ncp == NULL) return NC_ENOMEM; #if defined(LOCKNUMREC) /* && _CRAYMPP */ if (status = NC_init_pe(ncp, basepe)) { return status; } #else /* * !_CRAYMPP, only pe 0 is valid */ if(basepe != 0) return NC_EINVAL; #endif status = ncio_open(path, ioflags, 0, 0, &ncp->chunk, &ncp->nciop, 0); if(status) goto unwind_alloc; assert(ncp->flags == 0); if(fIsSet(ncp->nciop->ioflags, NC_SHARE)) { /* * NC_SHARE implies sync up the number of records as well. * (File format version one.) * Note that other header changes are not shared * automatically. Some sort of IPC (external to this package) * would be used to trigger a call to nc_sync(). */ fSet(ncp->flags, NC_NSYNC); } status = nc_get_NC(ncp); if(status != NC_NOERR) goto unwind_ioc; add_to_NCList(ncp); if(chunksizehintp != NULL) *chunksizehintp = ncp->chunk; *ncid_ptr = ncp->nciop->fd; return NC_NOERR; unwind_ioc: (void) ncio_close(ncp->nciop, 0); ncp->nciop = NULL; /*FALLTHRU*/ unwind_alloc: free_NC(ncp); return status; } int nc_open(const char * path, int ioflags, int *ncid_ptr) { return nc__open(path, ioflags, NULL, ncid_ptr); } int nc__enddef(int ncid, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(!NC_indef(ncp)) return(NC_ENOTINDEFINE); return (NC_endef(ncp, h_minfree, v_align, v_minfree, r_align)); } int nc_enddef(int ncid) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(!NC_indef(ncp)) return(NC_ENOTINDEFINE); /* return(NC_endef(ncp, 0, 4096, 0, 4096)); */ return (NC_endef(ncp, 0, 1, 0, 1)); } int nc_close(int ncid) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) { status = NC_endef(ncp, 0, 1, 0, 1); /* TODO: defaults */ if(status != NC_NOERR ) { (void) nc_abort(ncid); return status; } } else if(!NC_readonly(ncp)) { status = NC_sync(ncp); /* flush buffers before any filesize comparisons */ (void) ncp->nciop->sync(ncp->nciop); } /* * If file opened for writing and filesize is less than * what it should be (due to previous use of NOFILL mode), * pad it to correct size, as reported by NC_calcsize(). */ if (status == ENOERR) { off_t filesize; /* current size of open file */ off_t calcsize; /* calculated file size, from header */ status = ncio_filesize(ncp->nciop, &filesize); if(status != ENOERR) return status; status = NC_calcsize(ncp, &calcsize); if(status != NC_NOERR) return status; if(filesize < calcsize && !NC_readonly(ncp)) { status = ncio_pad_length(ncp->nciop, calcsize); if(status != ENOERR) return status; } } (void) ncio_close(ncp->nciop, 0); ncp->nciop = NULL; del_from_NCList(ncp); free_NC(ncp); return status; } int nc_delete(const char * path) { return nc_delete_mp(path, 0); } int nc_delete_mp(const char * path, int basepe) { NC *ncp; int status; size_t chunk = 512; ncp = new_NC(&chunk); if(ncp == NULL) return NC_ENOMEM; #if defined(LOCKNUMREC) /* && _CRAYMPP */ if (status = NC_init_pe(ncp, basepe)) { return status; } #else /* * !_CRAYMPP, only pe 0 is valid */ if(basepe != 0) return NC_EINVAL; #endif status = ncio_open(path, NC_NOWRITE, 0, 0, &ncp->chunk, &ncp->nciop, 0); if(status) goto unwind_alloc; assert(ncp->flags == 0); status = nc_get_NC(ncp); if(status != NC_NOERR) { /* Not a netcdf file, don't delete */ /* ??? is this the right semantic? what if it was just too big? */ (void) ncio_close(ncp->nciop, 0); } else { /* ncio_close does the unlink */ status = ncio_close(ncp->nciop, 1); /* ncio_close does the unlink */ } ncp->nciop = NULL; unwind_alloc: free_NC(ncp); return status; } /* * In data mode, same as ncclose. * In define mode, restore previous definition. * In create, remove the file. */ int nc_abort(int ncid) { int status; NC *ncp; int doUnlink; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; doUnlink = NC_IsNew(ncp); if(ncp->old != NULL) { /* a plain redef, not a create */ assert(!NC_IsNew(ncp)); assert(fIsSet(ncp->flags, NC_INDEF)); free_NC(ncp->old); ncp->old = NULL; fClr(ncp->flags, NC_INDEF); } else if(!NC_readonly(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } (void) ncio_close(ncp->nciop, doUnlink); ncp->nciop = NULL; del_from_NCList(ncp); free_NC(ncp); return NC_NOERR; } int nc_redef(int ncid) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; if(fIsSet(ncp->nciop->ioflags, NC_SHARE)) { /* read in from disk */ status = read_NC(ncp); if(status != NC_NOERR) return status; } ncp->old = dup_NC(ncp); if(ncp->old == NULL) return NC_ENOMEM; fSet(ncp->flags, NC_INDEF); return NC_NOERR; } int nc_inq(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *xtendimp) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(ndimsp != NULL) *ndimsp = (int) ncp->dims.nelems; if(nvarsp != NULL) *nvarsp = (int) ncp->vars.nelems; if(nattsp != NULL) *nattsp = (int) ncp->attrs.nelems; if(xtendimp != NULL) *xtendimp = find_NC_Udim(&ncp->dims, NULL); return NC_NOERR; } int nc_inq_ndims(int ncid, int *ndimsp) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(ndimsp != NULL) *ndimsp = (int) ncp->dims.nelems; return NC_NOERR; } int nc_inq_nvars(int ncid, int *nvarsp) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(nvarsp != NULL) *nvarsp = (int) ncp->vars.nelems; return NC_NOERR; } int nc_inq_natts(int ncid, int *nattsp) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(nattsp != NULL) *nattsp = (int) ncp->attrs.nelems; return NC_NOERR; } int nc_inq_unlimdim(int ncid, int *xtendimp) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(xtendimp != NULL) *xtendimp = find_NC_Udim(&ncp->dims, NULL); return NC_NOERR; } int nc_sync(int ncid) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; if(NC_readonly(ncp)) { return read_NC(ncp); } /* else, read/write */ status = NC_sync(ncp); if(status != NC_NOERR) return status; return ncp->nciop->sync(ncp->nciop); } int nc_set_fill(int ncid, int fillmode, int *old_mode_ptr) { int status; NC *ncp; int oldmode; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; oldmode = fIsSet(ncp->flags, NC_NOFILL) ? NC_NOFILL : NC_FILL; if(fillmode == NC_NOFILL) { fSet(ncp->flags, NC_NOFILL); } else if(fillmode == NC_FILL) { if(fIsSet(ncp->flags, NC_NOFILL)) { /* * We are changing back to fill mode * so do a sync */ status = NC_sync(ncp); if(status != NC_NOERR) return status; } fClr(ncp->flags, NC_NOFILL); } else { return NC_EINVAL; /* Invalid fillmode */ } if(old_mode_ptr != NULL) *old_mode_ptr = oldmode; return NC_NOERR; } #ifdef LOCKNUMREC /* create function versions of the NC_*_numrecs macros */ size_t NC_get_numrecs(const NC *ncp) { shmem_t numrec; shmem_short_get(&numrec, (shmem_t *) ncp->lock + LOCKNUMREC_VALUE, 1, ncp->lock[LOCKNUMREC_BASEPE]); return (size_t) numrec; } void NC_set_numrecs(NC *ncp, size_t nrecs) { shmem_t numrec = (shmem_t) nrecs; /* update local value too */ ncp->lock[LOCKNUMREC_VALUE] = (ushmem_t) numrec; shmem_short_put((shmem_t *) ncp->lock + LOCKNUMREC_VALUE, &numrec, 1, ncp->lock[LOCKNUMREC_BASEPE]); } void NC_increase_numrecs(NC *ncp, size_t nrecs) { /* this is only called in one place that's already protected * by a lock ... so don't worry about it */ if (nrecs > NC_get_numrecs(ncp)) NC_set_numrecs(ncp, nrecs); } #endif /* LOCKNUMREC */ /* everyone in communicator group will be executing this */ /*ARGSUSED*/ int nc_set_base_pe(int ncid, int pe) { #if _CRAYMPP && defined(LOCKNUMREC) int status; NC *ncp; shmem_t numrecs; if ((status = NC_check_id(ncid, &ncp)) != NC_NOERR) { return status; } if (pe < 0 || pe >= _num_pes()) { return NC_EINVAL; /* invalid base pe */ } numrecs = (shmem_t) NC_get_numrecs(ncp); ncp->lock[LOCKNUMREC_VALUE] = (ushmem_t) numrecs; /* update serving & lock values for a "smooth" transition */ /* note that the "real" server will being doing this as well */ /* as all the rest in the group */ /* must have syncronization before & after this step */ shmem_short_get( (shmem_t *) ncp->lock + LOCKNUMREC_SERVING, (shmem_t *) ncp->lock + LOCKNUMREC_SERVING, 1, ncp->lock[LOCKNUMREC_BASEPE]); shmem_short_get( (shmem_t *) ncp->lock + LOCKNUMREC_LOCK, (shmem_t *) ncp->lock + LOCKNUMREC_LOCK, 1, ncp->lock[LOCKNUMREC_BASEPE]); /* complete transition */ ncp->lock[LOCKNUMREC_BASEPE] = (ushmem_t) pe; #else /* _CRAYMPP && defined(LOCKNUMREC) */ (void)ncid; (void)pe; #endif /* _CRAYMPP && LOCKNUMREC */ return NC_NOERR; } /*ARGSUSED*/ int nc_inq_base_pe(int ncid, int *pe) { #if _CRAYMPP && defined(LOCKNUMREC) int status; NC *ncp; if ((status = NC_check_id(ncid, &ncp)) != NC_NOERR) { return status; } *pe = (int) ncp->lock[LOCKNUMREC_BASEPE]; #else /* * !_CRAYMPP, only pe 0 is valid */ *pe = 0; (void)ncid; #endif /* _CRAYMPP && LOCKNUMREC */ return NC_NOERR; } int nc_inq_format(int ncid, int *formatp) { int status; NC *ncp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; /* only need to check for netCDF-3 variants, since this is never called for netCDF-4 files */ *formatp = fIsSet(ncp->flags, NC_64BIT_OFFSET) ? NC_FORMAT_64BIT : NC_FORMAT_CLASSIC; return NC_NOERR; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/dim.c0000644000175000017500000002271211606020250021401 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: dim.c,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #include "nc.h" #include #include #include #include "ncx.h" #include "fbits.h" #if defined(_MSC_VER) && (_MSC_VER >= 1300) # pragma warning ( disable : 4127 ) /* conditional expression is constant */ #endif /* MSVC 7.1 */ /* * Free dim * Formerly NC_free_dim(dim) */ void free_NC_dim(NC_dim *dimp) { if(dimp == NULL) return; free_NC_string(dimp->name); free(dimp); } NC_dim * new_x_NC_dim(NC_string *name) { NC_dim *dimp; dimp = (NC_dim *) malloc(sizeof(NC_dim)); if(dimp == NULL) return NULL; dimp->name = name; dimp->size = 0; return(dimp); } /* * Formerly NC_new_dim(const char *name, long size) */ static NC_dim * new_NC_dim(const char *name, size_t size) { NC_string *strp; NC_dim *dimp; strp = new_NC_string(strlen(name), name); if(strp == NULL) return NULL; dimp = new_x_NC_dim(strp); if(dimp == NULL) { free_NC_string(strp); return NULL; } dimp->size = size; return(dimp); } static NC_dim * dup_NC_dim(const NC_dim *dimp) { return new_NC_dim(dimp->name->cp, dimp->size); } /* * Step thru NC_DIMENSION array, seeking the UNLIMITED dimension. * Return dimid or -1 on not found. * *dimpp is set to the appropriate NC_dim. * The loop structure is odd. In order to parallelize, * we moved a clearer 'break' inside the loop body to the loop test. */ int find_NC_Udim(const NC_dimarray *ncap, NC_dim **dimpp) { assert(ncap != NULL); if(ncap->nelems == 0) return -1; { int dimid = 0; NC_dim **loc = ncap->value; for(; (size_t) dimid < ncap->nelems && (*loc)->size != NC_UNLIMITED; dimid++, loc++) { /*EMPTY*/ } if((size_t)dimid >= ncap->nelems) return(-1); /* not found */ /* else, normal return */ if(dimpp != NULL) *dimpp = *loc; return dimid; } } /* * Step thru NC_DIMENSION array, seeking match on name. * Return dimid or -1 on not found. * *dimpp is set to the appropriate NC_dim. * The loop structure is odd. In order to parallelize, * we moved a clearer 'break' inside the loop body to the loop test. */ static int NC_finddim(const NC_dimarray *ncap, const char *name, NC_dim **dimpp) { assert(ncap != NULL); if(ncap->nelems == 0) return -1; { size_t slen = strlen(name); int dimid = 0; NC_dim **loc = (NC_dim **) ncap->value; for(; (size_t) dimid < ncap->nelems && (strlen((*loc)->name->cp) != slen || strncmp((*loc)->name->cp, name, slen) != 0); dimid++, loc++) { /*EMPTY*/ } if((size_t)dimid >= ncap->nelems) return(-1); /* not found */ /* else, normal return */ if(dimpp != NULL) *dimpp = *loc; return(dimid); } } /* dimarray */ /* * Free the stuff "in" (referred to by) an NC_dimarray. * Leaves the array itself allocated. */ void free_NC_dimarrayV0(NC_dimarray *ncap) { assert(ncap != NULL); if(ncap->nelems == 0) return; assert(ncap->value != NULL); { NC_dim **dpp = ncap->value; NC_dim *const *const end = &dpp[ncap->nelems]; for( /*NADA*/; dpp < end; dpp++) { free_NC_dim(*dpp); *dpp = NULL; } } ncap->nelems = 0; } /* * Free NC_dimarray values. * formerly NC_free_array() */ void free_NC_dimarrayV(NC_dimarray *ncap) { assert(ncap != NULL); if(ncap->nalloc == 0) return; assert(ncap->value != NULL); free_NC_dimarrayV0(ncap); free(ncap->value); ncap->value = NULL; ncap->nalloc = 0; } int dup_NC_dimarrayV(NC_dimarray *ncap, const NC_dimarray *ref) { int status = NC_NOERR; assert(ref != NULL); assert(ncap != NULL); if(ref->nelems != 0) { const size_t sz = ref->nelems * sizeof(NC_dim *); ncap->value = (NC_dim **) malloc(sz); if(ncap->value == NULL) return NC_ENOMEM; (void) memset(ncap->value, 0, sz); ncap->nalloc = ref->nelems; } ncap->nelems = 0; { NC_dim **dpp = ncap->value; const NC_dim **drpp = (const NC_dim **)ref->value; NC_dim *const *const end = &dpp[ref->nelems]; for( /*NADA*/; dpp < end; drpp++, dpp++, ncap->nelems++) { *dpp = dup_NC_dim(*drpp); if(*dpp == NULL) { status = NC_ENOMEM; break; } } } if(status != NC_NOERR) { free_NC_dimarrayV(ncap); return status; } assert(ncap->nelems == ref->nelems); return NC_NOERR; } /* * Add a new handle on the end of an array of handles * Formerly NC_incr_array(array, tail) */ static int incr_NC_dimarray(NC_dimarray *ncap, NC_dim *newelemp) { NC_dim **vp; assert(ncap != NULL); if(ncap->nalloc == 0) { assert(ncap->nelems == 0); vp = (NC_dim **) malloc(NC_ARRAY_GROWBY * sizeof(NC_dim *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc = NC_ARRAY_GROWBY; } else if(ncap->nelems +1 > ncap->nalloc) { vp = (NC_dim **) realloc(ncap->value, (ncap->nalloc + NC_ARRAY_GROWBY) * sizeof(NC_dim *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc += NC_ARRAY_GROWBY; } if(newelemp != NULL) { ncap->value[ncap->nelems] = newelemp; ncap->nelems++; } return NC_NOERR; } NC_dim * elem_NC_dimarray(const NC_dimarray *ncap, size_t elem) { assert(ncap != NULL); /* cast needed for braindead systems with signed size_t */ if(ncap->nelems == 0 || (unsigned long) elem >= ncap->nelems) return NULL; assert(ncap->value != NULL); return ncap->value[elem]; } /* Public */ int nc_def_dim(int ncid, const char *name, size_t size, int *dimidp) { int status; NC *ncp; int dimid; NC_dim *dimp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(!NC_indef(ncp)) return NC_ENOTINDEFINE; status = NC_check_name(name); if(status != NC_NOERR) return status; if ((ncp->flags & NC_64BIT_OFFSET) && sizeof(off_t) > 4) { /* CDF2 format and LFS */ if(size > X_UINT_MAX - 3) /* "- 3" handles rounded-up size */ return NC_EDIMSIZE; } else { /* CDF1 format */ if(size > X_INT_MAX - 3) return NC_EDIMSIZE; } if(size == NC_UNLIMITED) { dimid = find_NC_Udim(&ncp->dims, &dimp); if(dimid != -1) { assert(dimid != -1); return NC_EUNLIMIT; } } if(ncp->dims.nelems >= NC_MAX_DIMS) return NC_EMAXDIMS; dimid = NC_finddim(&ncp->dims, name, &dimp); if(dimid != -1) return NC_ENAMEINUSE; dimp = new_NC_dim(name, size); if(dimp == NULL) return NC_ENOMEM; status = incr_NC_dimarray(&ncp->dims, dimp); if(status != NC_NOERR) { free_NC_dim(dimp); return status; } if(dimidp != NULL) *dimidp = (int)ncp->dims.nelems -1; return NC_NOERR; } int nc_inq_dimid(int ncid, const char *name, int *dimid_ptr) { int status; NC *ncp; int dimid; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; dimid = NC_finddim(&ncp->dims, name, NULL); if(dimid == -1) return NC_EBADDIM; *dimid_ptr = dimid; return NC_NOERR; } int nc_inq_dim(int ncid, int dimid, char *name, size_t *sizep) { int status; NC *ncp; NC_dim *dimp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; dimp = elem_NC_dimarray(&ncp->dims, (size_t)dimid); if(dimp == NULL) return NC_EBADDIM; if(name != NULL) { (void)strncpy(name, dimp->name->cp, dimp->name->nchars); name[dimp->name->nchars] = 0; } if(sizep != 0) { if(dimp->size == NC_UNLIMITED) *sizep = NC_get_numrecs(ncp); else *sizep = dimp->size; } return NC_NOERR; } int nc_inq_dimname(int ncid, int dimid, char *name) { int status; NC *ncp; NC_dim *dimp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; dimp = elem_NC_dimarray(&ncp->dims, (size_t)dimid); if(dimp == NULL) return NC_EBADDIM; if(name != NULL) { (void)strncpy(name, dimp->name->cp, dimp->name->nchars); name[dimp->name->nchars] = 0; } return NC_NOERR; } int nc_inq_dimlen(int ncid, int dimid, size_t *lenp) { int status; NC *ncp; NC_dim *dimp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; dimp = elem_NC_dimarray(&ncp->dims, (size_t)dimid); if(dimp == NULL) return NC_EBADDIM; if(lenp != 0) { if(dimp->size == NC_UNLIMITED) *lenp = NC_get_numrecs(ncp); else *lenp = dimp->size; } return NC_NOERR; } int nc_rename_dim( int ncid, int dimid, const char *newname) { int status; NC *ncp; int existid; NC_dim *dimp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; status = NC_check_name(newname); if(status != NC_NOERR) return status; existid = NC_finddim(&ncp->dims, newname, &dimp); if(existid != -1) return NC_ENAMEINUSE; dimp = elem_NC_dimarray(&ncp->dims, (size_t)dimid); if(dimp == NULL) return NC_EBADDIM; if(NC_indef(ncp)) { NC_string *old = dimp->name; NC_string *newStr = new_NC_string(strlen(newname), newname); if(newStr == NULL) return NC_ENOMEM; dimp->name = newStr; free_NC_string(old); return NC_NOERR; } /* else, not in define mode */ status = set_NC_string(dimp->name, newname); if(status != NC_NOERR) return status; set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/.NoDartCoverage0000644000175000017500000000004711606020250023325 0ustar amckinstryamckinstry# do not do coverage in this directory xdmf-2.1.dfsg.1/Utilities/vtknetcdf/fbits.h0000644000175000017500000000120611606020250021737 0ustar amckinstryamckinstry/* * Copyright 1995, University Corporation for Atmospheric Research * See top level COPYRIGHT file for copying and redistribution conditions. */ /* $Id: fbits.h,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #ifndef _FBITS_H_ #define _FBITS_H_ /* * Macros for dealing with flag bits. */ #define fSet(t, f) ((t) |= (f)) #define fClr(t, f) ((t) &= ~(f)) #define fIsSet(t, f) ((t) & (f)) #define fMask(t, f) ((t) & ~(f)) /* * Propositions */ /* a implies b */ #define pIf(a,b) (!(a) || (b)) /* a if and only if b, use == when it makes sense */ #define pIff(a,b) (((a) && (b)) || (!(a) && !(b))) #endif /*!FBITS_H_*/ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/putget.m40000644000175000017500000015650011606020250022241 0ustar amckinstryamckinstrydnl This is m4 source. dnl Process using m4 to produce 'C' language file. dnl undefine(`begin')dnl undefine(`index')dnl undefine(`len')dnl dnl dnl If you see this line, you can ignore the next one. /* Do not edit this file. It is produced from the corresponding .m4 source */ dnl /* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: putget.m4,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #include "nc.h" #include #include #include #include "ncx.h" #include "fbits.h" #include "onstack.h" #ifdef LOCKNUMREC # include /* for SGI/Cray SHMEM routines */ # ifdef LN_TEST # include # endif #endif #ifdef __BORLANDC__ # pragma warn -8004 /* "assigned a value that is never used" */ # pragma warn -8065 /* "Call to function 'XXX' with no prototype" */ #endif #if defined(_MSC_VER) && (_MSC_VER >= 1400) # pragma warning ( disable : 4130 ) /* logical operation on address of string constant */ #endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ #undef MIN /* system may define MIN somewhere and complain */ #define MIN(mm,nn) (((mm) < (nn)) ? (mm) : (nn)) /* #define ODEBUG 1 */ #if ODEBUG #include /* * Print the values of an array of size_t */ void arrayp(const char *label, size_t count, const size_t *array) { (void) fprintf(stderr, "%s", label); (void) fputc('\t',stderr); for(; count > 0; count--, array++) (void) fprintf(stderr," %lu", (unsigned long)*array); (void) fputc('\n',stderr); } #endif /* ODEBUG */ /* * This is how much space is required by the user, as in * * vals = malloc(nel * nctypelen(var.type)); * ncvarget(cdfid, varid, cor, edg, vals); */ int nctypelen(nc_type type) { switch(type){ case NC_BYTE : case NC_CHAR : return((int)sizeof(char)); case NC_SHORT : return(int)(sizeof(short)); case NC_INT : return((int)sizeof(int)); case NC_FLOAT : return((int)sizeof(float)); case NC_DOUBLE : return((int)sizeof(double)); case NC_NAT: break; /* some compilers complain if enums are missing from a switch */ } return -1; } /* Begin fill */ /* * This is tunable parameter. * It essentially controls the tradeoff between the number of times * memcpy() gets called to copy the external data to fill * a large buffer vs the number of times its called to * prepare the external data. */ #if _SX /* NEC SX specific optimization */ #define NFILL 2048 #else #define NFILL 16 #endif dnl dnl NCFILL(Type, Xtype, XSize, Fill) dnl define(`NCFILL',dnl `dnl static int NC_fill_$2( void **xpp, size_t nelems) /* how many */ { $1 fillp[NFILL * sizeof(double)/$3]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { $1 *vp = fillp; /* lower bound of area to be filled */ const $1 *const end = vp + nelems; while(vp < end) { *vp++ = $4; } } return ncx_putn_$2_$1(xpp, nelems, fillp); } ')dnl /* * Next 6 type specific functions * Fill a some memory with the default special value. * Formerly NC_arrayfill() */ NCFILL(schar, schar, X_SIZEOF_CHAR, NC_FILL_BYTE) NCFILL(char, char, X_SIZEOF_CHAR, NC_FILL_CHAR) NCFILL(short, short, X_SIZEOF_SHORT, NC_FILL_SHORT) #if (SIZEOF_INT >= X_SIZEOF_INT) NCFILL(int, int, X_SIZEOF_INT, NC_FILL_INT) #elif SIZEOF_LONG == X_SIZEOF_INT NCFILL(long, int, X_SIZEOF_INT, NC_FILL_INT) #else #error "NC_fill_int implementation" #endif NCFILL(float, float, X_SIZEOF_FLOAT, NC_FILL_FLOAT) NCFILL(double, double, X_SIZEOF_DOUBLE, NC_FILL_DOUBLE) /* * Fill the external space for variable 'varp' values at 'recno' with * the appropriate value. If 'varp' is not a record variable, fill the * whole thing. For the special case when 'varp' is the only record * variable and it is of type byte, char, or short, varsize should be * ncp->recsize, otherwise it should be varp->len. * Formerly xdr_NC_fill() */ int fill_NC_var(NC *ncp, const NC_var *varp, size_t varsize, size_t recno) { char xfillp[NFILL * X_SIZEOF_DOUBLE]; const size_t step = varp->xsz; const size_t nelems = sizeof(xfillp)/step; const size_t xsz = varp->xsz * nelems; NC_attr **attrpp; off_t offset; size_t remaining = varsize; void *xp; int status; /* * Set up fill value */ attrpp = NC_findattr(&varp->attrs, _FillValue); if( attrpp != NULL ) { /* User defined fill value */ if( (*attrpp)->type != varp->type || (*attrpp)->nelems != 1 ) { return NC_EBADTYPE; } else { /* Use the user defined value */ char *cp = xfillp; const char *const end = &xfillp[sizeof(xfillp)]; assert(step <= (*attrpp)->xsz); for( /*NADA*/; cp < end; cp += step) { (void) memcpy(cp, (*attrpp)->xvalue, step); } } } else { /* use the default */ assert(xsz % X_ALIGN == 0); assert(xsz <= sizeof(xfillp)); xp = xfillp; switch(varp->type){ case NC_BYTE : status = NC_fill_schar(&xp, nelems); break; case NC_CHAR : status = NC_fill_char(&xp, nelems); break; case NC_SHORT : status = NC_fill_short(&xp, nelems); break; case NC_INT : status = NC_fill_int(&xp, nelems); break; case NC_FLOAT : status = NC_fill_float(&xp, nelems); break; case NC_DOUBLE : status = NC_fill_double(&xp, nelems); break; default : assert("fill_NC_var invalid type" == 0); status = NC_EBADTYPE; break; } if(status != NC_NOERR) return status; assert(xp == xfillp + xsz); } /* * copyout: * xfillp now contains 'nelems' elements of the fill value * in external representation. */ /* * Copy it out. */ offset = varp->begin; if(IS_RECVAR(varp)) { offset += (off_t)ncp->recsize * recno; } assert(remaining > 0); for(;;) { const size_t chunksz = MIN(remaining, ncp->chunk); size_t ii; status = ncp->nciop->get(ncp->nciop, offset, chunksz, RGN_WRITE, &xp); if(status != NC_NOERR) { return status; } /* * fill the chunksz buffer in units of xsz */ for(ii = 0; ii < chunksz/xsz; ii++) { (void) memcpy(xp, xfillp, xsz); xp = (char *)xp + xsz; } /* * Deal with any remainder */ { const size_t rem = chunksz % xsz; if(rem != 0) { (void) memcpy(xp, xfillp, rem); /* xp = (char *)xp + xsz; */ } } status = ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); if(status != NC_NOERR) { break; } remaining -= chunksz; if(remaining == 0) break; /* normal loop exit */ offset += chunksz; } return status; } /* End fill */ /* * Add a record containing the fill values. */ static int NCfillrecord(NC *ncp, const NC_var *const *varpp, size_t recno) { size_t ii = 0; for(; ii < ncp->vars.nelems; ii++, varpp++) { if( !IS_RECVAR(*varpp) ) { continue; /* skip non-record variables */ } { const int status = fill_NC_var(ncp, *varpp, (*varpp)->len, recno); if(status != NC_NOERR) return status; } } return NC_NOERR; } /* * Add a record containing the fill values in the special case when * there is exactly one record variable, where we don't require each * record to be four-byte aligned (no record padding). */ static int NCfillspecialrecord(NC *ncp, const NC_var *varp, size_t recno) { int status; assert(IS_RECVAR(varp)); status = fill_NC_var(ncp, varp, ncp->recsize, recno); if(status != NC_NOERR) return status; return NC_NOERR; } /* * It is advantageous to * #define TOUCH_LAST * when using memory mapped io. */ #if TOUCH_LAST /* * Grow the file to a size which can contain recno */ static int NCtouchlast(NC *ncp, const NC_var *const *varpp, size_t recno) { int status = NC_NOERR; const NC_var *varp = NULL; { size_t ii = 0; for(; ii < ncp->vars.nelems; ii++, varpp++) { if( !IS_RECVAR(*varpp) ) { continue; /* skip non-record variables */ } varp = *varpp; } } assert(varp != NULL); assert( IS_RECVAR(varp) ); { const off_t offset = varp->begin + (off_t)(recno-1) * (off_t)ncp->recsize + (off_t)(varp->len - varp->xsz); void *xp; status = ncp->nciop->get(ncp->nciop, offset, varp->xsz, RGN_WRITE, &xp); if(status != NC_NOERR) return status; (void)memset(xp, 0, varp->xsz); status = ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); } return status; } #endif /* TOUCH_LAST */ /* * Ensure that the netcdf file has 'numrecs' records, * add records and fill as neccessary. */ static int NCvnrecs(NC *ncp, size_t numrecs) { int status = NC_NOERR; #ifdef LOCKNUMREC ushmem_t myticket = 0, nowserving = 0; ushmem_t numpe = (ushmem_t) _num_pes(); /* get ticket and wait */ myticket = shmem_short_finc((shmem_t *) ncp->lock + LOCKNUMREC_LOCK, ncp->lock[LOCKNUMREC_BASEPE]); #ifdef LN_TEST fprintf(stderr,"%d of %d : ticket = %hu\n", _my_pe(), _num_pes(), myticket); #endif do { shmem_short_get((shmem_t *) &nowserving, (shmem_t *) ncp->lock + LOCKNUMREC_SERVING, 1, ncp->lock[LOCKNUMREC_BASEPE]); #ifdef LN_TEST fprintf(stderr,"%d of %d : serving = %hu\n", _my_pe(), _num_pes(), nowserving); #endif /* work-around for non-unique tickets */ if (nowserving > myticket && nowserving < myticket + numpe ) { /* get a new ticket ... you've been bypassed */ /* and handle the unlikely wrap-around effect */ myticket = shmem_short_finc( (shmem_t *) ncp->lock + LOCKNUMREC_LOCK, ncp->lock[LOCKNUMREC_BASEPE]); #ifdef LN_TEST fprintf(stderr,"%d of %d : new ticket = %hu\n", _my_pe(), _num_pes(), myticket); #endif } } while(nowserving != myticket); /* now our turn to check & update value */ #endif if(numrecs > NC_get_numrecs(ncp)) { #if TOUCH_LAST status = NCtouchlast(ncp, (const NC_var *const*)ncp->vars.value, numrecs); if(status != NC_NOERR) goto common_return; #endif /* TOUCH_LAST */ set_NC_ndirty(ncp); if(!NC_dofill(ncp)) { /* Simply set the new numrecs value */ NC_set_numrecs(ncp, numrecs); } else { /* Treat two cases differently: - exactly one record variable (no padding) - multiple record variables (each record padded to 4-byte alignment) */ NC_var **vpp = (NC_var **)ncp->vars.value; NC_var *const *const end = &vpp[ncp->vars.nelems]; NC_var *recvarp = NULL; /* last record var */ int numrecvars = 0; size_t cur_nrecs; /* determine how many record variables */ for( /*NADA*/; vpp < end; vpp++) { if(IS_RECVAR(*vpp)) { recvarp = *vpp; numrecvars++; } } if (numrecvars != 1) { /* usual case */ /* Fill each record out to numrecs */ while((cur_nrecs = NC_get_numrecs(ncp)) < numrecs) { status = NCfillrecord(ncp, (const NC_var *const*)ncp->vars.value, cur_nrecs); if(status != NC_NOERR) { break; } NC_increase_numrecs(ncp, cur_nrecs +1); } if(status != NC_NOERR) goto common_return; } else { /* special case */ /* Fill each record out to numrecs */ while((cur_nrecs = NC_get_numrecs(ncp)) < numrecs) { status = NCfillspecialrecord(ncp, recvarp, cur_nrecs); if(status != NC_NOERR) { break; } NC_increase_numrecs(ncp, cur_nrecs +1); } if(status != NC_NOERR) goto common_return; } } if(NC_doNsync(ncp)) { status = write_numrecs(ncp); } } common_return: #ifdef LOCKNUMREC /* finished with our lock - increment serving number */ (void) shmem_short_finc((shmem_t *) ncp->lock + LOCKNUMREC_SERVING, ncp->lock[LOCKNUMREC_BASEPE]); #endif return status; } /* * Check whether 'coord' values are valid for the variable. */ static int NCcoordck(NC *ncp, const NC_var *varp, const size_t *coord) { const size_t *ip; size_t *up; if(varp->ndims == 0) return NC_NOERR; /* 'scalar' variable */ if(IS_RECVAR(varp)) { if(*coord > X_INT_MAX) return NC_EINVALCOORDS; /* sanity check */ if(NC_readonly(ncp) && *coord >= NC_get_numrecs(ncp)) { if(!NC_doNsync(ncp)) return NC_EINVALCOORDS; /* else */ { /* Update from disk and check again */ const int status = read_numrecs(ncp); if(status != NC_NOERR) return status; if(*coord >= NC_get_numrecs(ncp)) return NC_EINVALCOORDS; } } ip = coord + 1; up = varp->shape + 1; } else { ip = coord; up = varp->shape; } #ifdef CDEBUG fprintf(stderr," NCcoordck: coord %ld, count %d, ip %ld\n", coord, varp->ndims, ip ); #endif /* CDEBUG */ for(; ip < coord + varp->ndims; ip++, up++) { #ifdef CDEBUG fprintf(stderr," NCcoordck: ip %p, *ip %ld, up %p, *up %lu\n", ip, *ip, up, *up ); #endif /* CDEBUG */ /* cast needed for braindead systems with signed size_t */ if((unsigned long) *ip >= (unsigned long) *up ) return NC_EINVALCOORDS; } return NC_NOERR; } /* * Check whether 'edges' are valid for the variable and 'start' */ /*ARGSUSED*/ static int NCedgeck(const NC *ncp, const NC_var *varp, const size_t *start, const size_t *edges) { const size_t *const end = start + varp->ndims; const size_t *shp = varp->shape; (void)ncp; if(varp->ndims == 0) return NC_NOERR; /* 'scalar' variable */ if(IS_RECVAR(varp)) { start++; edges++; shp++; } for(; start < end; start++, edges++, shp++) { /* cast needed for braindead systems with signed size_t */ if((unsigned long) *edges > *shp || (unsigned long) *start + (unsigned long) *edges > *shp) { return(NC_EEDGE); } } return NC_NOERR; } /* * Translate the (variable, coord) pair into a seek index */ static off_t NC_varoffset(const NC *ncp, const NC_var *varp, const size_t *coord) { if(varp->ndims == 0) /* 'scalar' variable */ return varp->begin; if(varp->ndims == 1) { if(IS_RECVAR(varp)) return varp->begin + (off_t)(*coord) * (off_t)ncp->recsize; /* else */ return varp->begin + (off_t)(*coord) * (off_t)varp->xsz; } /* else */ { off_t lcoord = (off_t)coord[varp->ndims -1]; size_t *up = varp->dsizes +1; const size_t *ip = coord; const size_t *const end = varp->dsizes + varp->ndims; if(IS_RECVAR(varp)) up++, ip++; for(; up < end; up++, ip++) lcoord += *up * *ip; lcoord *= varp->xsz; if(IS_RECVAR(varp)) lcoord += (off_t)(*coord) * ncp->recsize; lcoord += varp->begin; return lcoord; } } dnl dnl Output 'nelems' items of contiguous data of type "Type" dnl for variable 'varp' at 'start'. dnl "Xtype" had better match 'varp->type'. dnl--- dnl dnl PUTNCVX(Xtype, Type) dnl define(`PUTNCVX',dnl `dnl static int putNCvx_$1_$2(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const $2 *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_$1_$2(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } ')dnl PUTNCVX(char, char) PUTNCVX(schar, schar) PUTNCVX(schar, uchar) PUTNCVX(schar, short) PUTNCVX(schar, int) PUTNCVX(schar, long) PUTNCVX(schar, float) PUTNCVX(schar, double) PUTNCVX(short, schar) PUTNCVX(short, uchar) PUTNCVX(short, short) PUTNCVX(short, int) PUTNCVX(short, long) PUTNCVX(short, float) PUTNCVX(short, double) PUTNCVX(int, schar) PUTNCVX(int, uchar) PUTNCVX(int, short) PUTNCVX(int, int) PUTNCVX(int, long) PUTNCVX(int, float) PUTNCVX(int, double) PUTNCVX(float, schar) PUTNCVX(float, uchar) PUTNCVX(float, short) PUTNCVX(float, int) PUTNCVX(float, long) PUTNCVX(float, float) PUTNCVX(float, double) PUTNCVX(double, schar) PUTNCVX(double, uchar) PUTNCVX(double, short) PUTNCVX(double, int) PUTNCVX(double, long) PUTNCVX(double, float) PUTNCVX(double, double) dnl dnl PUTNCV(Type) dnl define(`PUTNCV',dnl `dnl static int putNCv_$1(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const $1 *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_$1(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_$1(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_$1(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_$1(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_$1(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } ')dnl static int putNCv_text(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const char *value) { if(varp->type != NC_CHAR) return NC_ECHAR; return putNCvx_char_char(ncp, varp, start, nelems, value); } PUTNCV(schar) PUTNCV(uchar) PUTNCV(short) PUTNCV(int) PUTNCV(long) PUTNCV(float) PUTNCV(double) dnl dnl GETNCVX(XType, Type) dnl define(`GETNCVX',dnl `dnl static int getNCvx_$1_$2(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, $2 *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_$1_$2(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } ')dnl GETNCVX(char, char) GETNCVX(schar, schar) GETNCVX(schar, uchar) GETNCVX(schar, short) GETNCVX(schar, int) GETNCVX(schar, long) GETNCVX(schar, float) GETNCVX(schar, double) GETNCVX(short, schar) GETNCVX(short, uchar) GETNCVX(short, short) GETNCVX(short, int) GETNCVX(short, long) GETNCVX(short, float) GETNCVX(short, double) GETNCVX(int, schar) GETNCVX(int, uchar) GETNCVX(int, short) GETNCVX(int, int) GETNCVX(int, long) GETNCVX(int, float) GETNCVX(int, double) GETNCVX(float, schar) GETNCVX(float, uchar) GETNCVX(float, short) GETNCVX(float, int) GETNCVX(float, long) GETNCVX(float, float) GETNCVX(float, double) GETNCVX(double, schar) GETNCVX(double, uchar) GETNCVX(double, short) GETNCVX(double, int) GETNCVX(double, long) GETNCVX(double, float) GETNCVX(double, double) dnl dnl GETNCV(Type) dnl define(`GETNCV',dnl `dnl static int getNCv_$1(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, $1 *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_$1(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_$1(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_$1(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_$1(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_$1(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } ')dnl GETNCV(schar) GETNCV(uchar) GETNCV(short) GETNCV(int) GETNCV(long) GETNCV(float) GETNCV(double) static int getNCv_text(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, char *value) { if(varp->type != NC_CHAR) return NC_ECHAR; return getNCvx_char_char(ncp, varp, start, nelems, value); } /* * Copy 'nbytes' contiguous external values * from ('inncp', invp', inncoord') * to ('outncp', 'outvp', 'outcoord') * 'inncp' shouldn't be the same as 'outncp'. * Used only by ncvarcopy() */ static int NCxvarcpy(NC *inncp, NC_var *invp, size_t *incoord, NC *outncp, NC_var *outvp, size_t *outcoord, size_t nbytes) { int status; off_t inoffset = NC_varoffset(inncp, invp, incoord); off_t outoffset = NC_varoffset(outncp, outvp, outcoord); void *inxp; void *outxp; const size_t chunk = MIN(inncp->chunk, outncp->chunk); do { const size_t extent = MIN(nbytes, chunk); status = inncp->nciop->get(inncp->nciop, inoffset, extent, 0, &inxp); if(status != NC_NOERR) return status; status = outncp->nciop->get(outncp->nciop, outoffset, extent, RGN_WRITE, &outxp); if(status != NC_NOERR) { (void) inncp->nciop->rel(inncp->nciop, inoffset, 0); break; } (void) memcpy(outxp, inxp, extent); status = outncp->nciop->rel(outncp->nciop, outoffset, RGN_MODIFIED); (void) inncp->nciop->rel(inncp->nciop, inoffset, 0); nbytes -= extent; if(nbytes == 0) break; /* normal loop exit */ inoffset += extent; outoffset += extent; } while (status == NC_NOERR); return status; } /* * For ncvar{put,get}, * find the largest contiguous block from within 'edges'. * returns the index to the left of this (which may be -1). * Compute the number of contiguous elements and return * that in *iocountp. * The presence of "record" variables makes this routine * overly subtle. */ static int NCiocount(const NC *const ncp, const NC_var *const varp, const size_t *const edges, size_t *const iocountp) { const size_t *edp0 = edges; const size_t *edp = edges + varp->ndims; const size_t *shp = varp->shape + varp->ndims; if(IS_RECVAR(varp)) { if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only 'record' variable */ *iocountp = *edges; return(0); } /* else */ edp0++; } assert(edges != NULL); /* find max contiguous */ while(edp > edp0) { shp--; edp--; if(*edp < *shp ) { const size_t *zedp = edp; while(zedp >= edp0) { if(*zedp == 0) { *iocountp = 0; goto done; } /* Tip of the hat to segmented architectures */ if(zedp == edp0) break; zedp--; } break; } assert(*edp == *shp); } /* * edp, shp reference rightmost index s.t. *(edp +1) == *(shp +1) * * Or there is only one dimension. * If there is only one dimension and it is 'non record' dimension, * edp is &edges[0] and we will return -1. * If there is only one dimension and and it is a "record dimension", * edp is &edges[1] (out of bounds) and we will return 0; */ assert(shp >= varp->shape + varp->ndims -1 || *(edp +1) == *(shp +1)); /* now accumulate max count for a single io operation */ for(*iocountp = 1, edp0 = edp; edp0 < edges + varp->ndims; edp0++) { *iocountp *= *edp0; } done: return((int)(edp - edges) - 1); } /* * Set the elements of the array 'upp' to * the sum of the corresponding elements of * 'stp' and 'edp'. 'end' should be &stp[nelems]. */ static void set_upper(size_t *upp, /* modified on return */ const size_t *stp, const size_t *edp, const size_t *const end) { while(upp < end) { *upp++ = *stp++ + *edp++; } } /* * The infamous and oft-discussed odometer code. * * 'start[]' is the starting coordinate. * 'upper[]' is the upper bound s.t. start[ii] < upper[ii]. * 'coord[]' is the register, the current coordinate value. * For some ii, * upp == &upper[ii] * cdp == &coord[ii] * * Running this routine increments *cdp. * * If after the increment, *cdp is equal to *upp * (and cdp is not the leftmost dimension), * *cdp is "zeroed" to the starting value and * we need to "carry", eg, increment one place to * the left. * * TODO: Some architectures hate recursion? * Reimplement non-recursively. */ static void odo1(const size_t *const start, const size_t *const upper, size_t *const coord, /* modified on return */ const size_t *upp, size_t *cdp) { assert(coord <= cdp && cdp <= coord + NC_MAX_VAR_DIMS); assert(upper <= upp && upp <= upper + NC_MAX_VAR_DIMS); assert(upp - upper == cdp - coord); assert(*cdp <= *upp); (*cdp)++; if(cdp != coord && *cdp >= *upp) { *cdp = start[cdp - coord]; odo1(start, upper, coord, upp -1, cdp -1); } } #ifdef _CRAYC #pragma _CRI noinline odo1 #endif dnl dnl NCTEXTCOND(Abbrv) dnl This is used inside the NC{PUT,GET} macros below dnl define(`NCTEXTCOND',dnl `dnl ifelse($1, text,dnl `dnl if(varp->type != NC_CHAR) return NC_ECHAR; ',dnl `dnl if(varp->type == NC_CHAR) return NC_ECHAR; ')dnl ')dnl /* Public */ dnl dnl NCPUTVAR1(Abbrev, Type) dnl define(`NCPUTVAR1',dnl `dnl int nc_put_var1_$1(int ncid, int varid, const size_t *coord, const $2 *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ NCTEXTCOND($1) status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_$1(ncp, varp, coord, 1, value); } ')dnl NCPUTVAR1(text, char) NCPUTVAR1(uchar, uchar) NCPUTVAR1(schar, schar) NCPUTVAR1(short, short) NCPUTVAR1(int, int) NCPUTVAR1(long, long) NCPUTVAR1(float, float) NCPUTVAR1(double, double) dnl dnl NCGETVAR1(Abbrv, Type) dnl define(`NCGETVAR1',dnl `dnl int nc_get_var1_$1(int ncid, int varid, const size_t *coord, $2 *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ NCTEXTCOND($1) status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_$1(ncp, varp, coord, 1, value); } ')dnl NCGETVAR1(text, char) NCGETVAR1(uchar, uchar) NCGETVAR1(schar, schar) NCGETVAR1(short, short) NCGETVAR1(int, int) NCGETVAR1(long, long) NCGETVAR1(float, float) NCGETVAR1(double, double) dnl dnl NCPUTVARA(Abbrv, Type) dnl define(`NCPUTVARA',dnl `dnl int nc_put_vara_$1(int ncid, int varid, const size_t *start, const size_t *edges, const $2 *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ NCTEXTCOND($1) status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_$1(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_$1(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_$1(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_$1(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index], &coord[index]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } ')dnl NCPUTVARA(text, char) NCPUTVARA(uchar, uchar) NCPUTVARA(schar, schar) NCPUTVARA(short, short) NCPUTVARA(int, int) NCPUTVARA(long, long) NCPUTVARA(float, float) NCPUTVARA(double, double) dnl dnl NCGETVARA(Abbrv, Type) dnl define(`NCGETVARA',dnl `dnl int nc_get_vara_$1(int ncid, int varid, const size_t *start, const size_t *edges, $2 *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ NCTEXTCOND($1) status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_$1(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_$1(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_$1(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_$1(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index], &coord[index]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } ')dnl NCGETVARA(text, char) NCGETVARA(uchar, uchar) NCGETVARA(schar, schar) NCGETVARA(short, short) NCGETVARA(int, int) NCGETVARA(long, long) NCGETVARA(float, float) NCGETVARA(double, double) #if defined(__cplusplus) /* C++ consts default to internal linkage and must be initialized */ const size_t coord_zero[NC_MAX_VAR_DIMS] = {0}; #else # if defined(_MSC_VER) && _MSC_VER >= 1300 static const size_t coord_zero[NC_MAX_VAR_DIMS] = { 0 }; # else static const size_t coord_zero[NC_MAX_VAR_DIMS]; # endif #endif dnl dnl NCPUTVAR(Abbrev, Type) dnl define(`NCPUTVAR',dnl `dnl int nc_put_var_$1(int ncid, int varid, const $2 *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ NCTEXTCOND($1) if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_$1(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_$1(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_$1(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_$1(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } ')dnl NCPUTVAR(text, char) NCPUTVAR(uchar, uchar) NCPUTVAR(schar, schar) NCPUTVAR(short, short) NCPUTVAR(int, int) NCPUTVAR(long, long) NCPUTVAR(float, float) NCPUTVAR(double, double) dnl dnl NCGETVAR(Abbrv, Type) dnl define(`NCGETVAR',dnl `dnl int nc_get_var_$1(int ncid, int varid, $2 *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_$1(ncp, varp, &zed, 1, value) ); } NCTEXTCOND($1) if(!IS_RECVAR(varp)) { return(getNCv_$1(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_$1(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_$1(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } ')dnl NCGETVAR(text, char) NCGETVAR(uchar, uchar) NCGETVAR(schar, schar) NCGETVAR(short, short) NCGETVAR(int, int) NCGETVAR(long, long) NCGETVAR(float, float) NCGETVAR(double, double) /* Begin putgetg.c */ dnl dnl NC_VARM_Upper_Body(void) dnl define(`NC_VARM_Upper_Body',dnl `dnl int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } ')dnl dnl dnl NC_VARM_Mid_Body(put_or_get, Abbrv) dnl define(`NC_VARM_Mid_Body',dnl `dnl varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; NCTEXTCOND($2) maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return $1 (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } ')dnl dnl dnl NC_VARM_Lower_Body(put_or_get) dnl define(`NC_VARM_Lower_Body',dnl `dnl /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvar$1() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = $1 (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; ')dnl dnl dnl NCGETVARS(Abbrv, Type) dnl define(`NCGETVARS',dnl `dnl int nc_get_vars_$1 ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, $2 *value) { return nc_get_varm_$1 (ncid, varid, start, edges, stride, 0, value); } ')dnl NCGETVARS(text, char) NCGETVARS(uchar, uchar) NCGETVARS(schar, schar) NCGETVARS(short, short) NCGETVARS(int, int) NCGETVARS(long, long) NCGETVARS(float, float) NCGETVARS(double, double) dnl dnl NCPUTVARS(Abbrv, Type) dnl define(`NCPUTVARS',dnl `dnl int nc_put_vars_$1 ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const $2 *value) { return nc_put_varm_$1 (ncid, varid, start, edges, stride, 0, value); } ')dnl NCPUTVARS(text, char) NCPUTVARS(uchar, uchar) NCPUTVARS(schar, schar) NCPUTVARS(short, short) NCPUTVARS(int, int) NCPUTVARS(long, long) NCPUTVARS(float, float) NCPUTVARS(double, double) /* * Generalized hyperslab input. */ dnl dnl NCGETVARM(Abbrv, Type) dnl define(`NCGETVARM',dnl `dnl int nc_get_varm_$1(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, $2 *value) { NC_VARM_Upper_Body() NC_VARM_Mid_Body(getNCv_$1, $1) /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } NC_VARM_Lower_Body(nc_get_vara_$1) } ')dnl NCGETVARM(text, char) NCGETVARM(uchar, uchar) NCGETVARM(schar, schar) NCGETVARM(short, short) NCGETVARM(int, int) NCGETVARM(long, long) NCGETVARM(float, float) NCGETVARM(double, double) #ifdef NO_NETCDF_2 extern int nctypelen(nc_type datatype); #endif /* * Generalized hyperslab output. */ dnl dnl NCPUTVARM(Abbrv, Type) dnl define(`NCPUTVARM',dnl `dnl int nc_put_varm_$1(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const $2 *value) { NC_VARM_Upper_Body() if (NC_readonly (ncp)) return NC_EPERM; NC_VARM_Mid_Body(putNCv_$1, $1) /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } NC_VARM_Lower_Body(nc_put_vara_$1) } ')dnl NCPUTVARM(text, char) NCPUTVARM(uchar, uchar) NCPUTVARM(schar, schar) NCPUTVARM(short, short) NCPUTVARM(int, int) NCPUTVARM(long, long) NCPUTVARM(float, float) NCPUTVARM(double, double) /* * Copy the values of a variable from an input netCDF to an output netCDF. * Input and output var assummed to have the same shape. * return -1 on error. */ int nc_copy_var(int ncid_in, int varid, int ncid_out) { int status = NC_NOERR; NC *inncp, *outncp; NC_var *invp, *outvp; status = NC_check_id(ncid_in, &inncp); if(status != NC_NOERR) return status; if(NC_indef(inncp)) { return NC_EINDEFINE; } status = NC_check_id(ncid_out, &outncp); if(status != NC_NOERR) return status; if(NC_readonly(outncp)) { /* output file isn't writable */ return NC_EPERM; } if(NC_indef(outncp)) { return NC_EINDEFINE; } /* find the variable in the input cdf */ invp = NC_lookupvar(inncp, varid); if(invp == NULL) { return NC_ENOTVAR; } /* find the variable in the output cdf */ if(NC_findvar(&outncp->vars, invp->name->cp, &outvp) == -1) { return NC_ENOTVAR; } /* can we even attempt to copy without conversion? */ if(outvp->type != invp->type) { return NC_EINVAL; } if( (invp->ndims == 0 && outvp->ndims != 0) || (invp->ndims != 0 && outvp->ndims == 0) || (IS_RECVAR(invp) && !IS_RECVAR(outvp)) || (!IS_RECVAR(invp) && IS_RECVAR(outvp)) || (invp->len != outvp->len) ) { return NC_EINVAL; } /* * Check coordinates */ { ALLOC_ONSTACK(coord, size_t, invp->ndims); const size_t nrecs = NC_get_numrecs(inncp); (void) memcpy(coord, invp->shape, invp->ndims * sizeof(size_t)); if(IS_RECVAR(invp)) *coord = nrecs; { size_t ii = 0; for(; ii < invp->ndims; ii++) coord[ii] --; } /* at this point, coord is the largest valid coord of invp */ if(NCcoordck(outncp, outvp, coord) != NC_NOERR) { return NC_EINVAL; } /* else */ (void) memset(coord, 0, invp->ndims * sizeof(size_t)); if(!IS_RECVAR(invp)) { status = NCxvarcpy(inncp, invp, coord, outncp, outvp, coord, invp->len); goto done; } /* else */ status = NCvnrecs(outncp, nrecs); if(status != NC_NOERR) goto done; for( /*NADA*/; *coord < nrecs; (*coord)++) { status = NCxvarcpy(inncp, invp, coord, outncp, outvp, coord, invp->len); if(status != NC_NOERR) break; } done: FREE_ONSTACK(coord); } return status; } /* no longer deprecated, used to support the 2.x interface and also the netcdf-4 api. */ int nc_get_att(int ncid, int varid, const char *name, void *value) { int status; nc_type atttype; status = nc_inq_atttype(ncid, varid, name, &atttype); if(status != NC_NOERR) return status; switch (atttype) { case NC_BYTE: return nc_get_att_schar(ncid, varid, name, (schar *)value); case NC_CHAR: return nc_get_att_text(ncid, varid, name, (char *)value); case NC_SHORT: return nc_get_att_short(ncid, varid, name, (short *)value); case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) return nc_get_att_int(ncid, varid, name, (int *)value); #elif SIZEOF_LONG == X_SIZEOF_INT return nc_get_att_long(ncid, varid, name, (long *)value); #endif case NC_FLOAT: return nc_get_att_float(ncid, varid, name, (float *)value); case NC_DOUBLE: return nc_get_att_double(ncid, varid, name, (double *)value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_put_att( int ncid, int varid, const char *name, nc_type type, size_t nelems, const void *value) { switch (type) { case NC_BYTE: return nc_put_att_schar(ncid, varid, name, type, nelems, (schar *)value); case NC_CHAR: return nc_put_att_text(ncid, varid, name, nelems, (char *)value); case NC_SHORT: return nc_put_att_short(ncid, varid, name, type, nelems, (short *)value); case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) return nc_put_att_int(ncid, varid, name, type, nelems, (int *)value); #elif SIZEOF_LONG == X_SIZEOF_INT return nc_put_att_long(ncid, varid, name, type, nelems, (long *)value); #endif case NC_FLOAT: return nc_put_att_float(ncid, varid, name, type, nelems, (float *)value); case NC_DOUBLE: return nc_put_att_double(ncid, varid, name, type, nelems, (double *)value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_get_var1(int ncid, int varid, const size_t *coord, void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_get_var1_text(ncid, varid, coord, (char *) value); case NC_BYTE: return nc_get_var1_schar(ncid, varid, coord, (schar *) value); case NC_SHORT: return nc_get_var1_short(ncid, varid, coord, (short *) value); case NC_INT: return nc_get_var1_int(ncid, varid, coord, (int *) value); case NC_FLOAT: return nc_get_var1_float(ncid, varid, coord, (float *) value); case NC_DOUBLE: return nc_get_var1_double(ncid, varid, coord, (double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_put_var1(int ncid, int varid, const size_t *coord, const void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_put_var1_text(ncid, varid, coord, (const char *) value); case NC_BYTE: return nc_put_var1_schar(ncid, varid, coord, (const schar *) value); case NC_SHORT: return nc_put_var1_short(ncid, varid, coord, (const short *) value); case NC_INT: return nc_put_var1_int(ncid, varid, coord, (const int *) value); case NC_FLOAT: return nc_put_var1_float(ncid, varid, coord, (const float *) value); case NC_DOUBLE: return nc_put_var1_double(ncid, varid, coord, (const double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_get_vara(int ncid, int varid, const size_t *start, const size_t *edges, void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_get_vara_text(ncid, varid, start, edges, (char *) value); case NC_BYTE: return nc_get_vara_schar(ncid, varid, start, edges, (schar *) value); case NC_SHORT: return nc_get_vara_short(ncid, varid, start, edges, (short *) value); case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) return nc_get_vara_int(ncid, varid, start, edges, (int *) value); #elif SIZEOF_LONG == X_SIZEOF_INT return nc_get_vara_long(ncid, varid, start, edges, (long *) value); #else #error "nc_get_vara implementation" #endif case NC_FLOAT: return nc_get_vara_float(ncid, varid, start, edges, (float *) value); case NC_DOUBLE: return nc_get_vara_double(ncid, varid, start, edges, (double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_put_vara(int ncid, int varid, const size_t *start, const size_t *edges, const void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_put_vara_text(ncid, varid, start, edges, (const char *) value); case NC_BYTE: return nc_put_vara_schar(ncid, varid, start, edges, (const schar *) value); case NC_SHORT: return nc_put_vara_short(ncid, varid, start, edges, (const short *) value); case NC_INT: return nc_put_vara_int(ncid, varid, start, edges, (const int *) value); case NC_FLOAT: return nc_put_vara_float(ncid, varid, start, edges, (const float *) value); case NC_DOUBLE: return nc_put_vara_double(ncid, varid, start, edges, (const double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_get_varm ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const ptrdiff_t * imapp, void *value) { int status; nc_type vartype; int varndims; ptrdiff_t *cvtmap = NULL; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; status = nc_inq_varndims(ncid, varid, &varndims); if(status != NC_NOERR) return status; if(imapp != NULL && varndims != 0) { /* * convert map units from bytes to units of sizeof(type) */ size_t ii; const ptrdiff_t szof = (ptrdiff_t) nctypelen(vartype); cvtmap = (ptrdiff_t *)calloc(varndims, sizeof(ptrdiff_t)); if(cvtmap == NULL) return NC_ENOMEM; for(ii = 0; (int)ii < varndims; ii++) { if(imapp[ii] % szof != 0) { free(cvtmap); return NC_EINVAL; } cvtmap[ii] = imapp[ii] / szof; } imapp = cvtmap; } switch(vartype){ case NC_CHAR: status = nc_get_varm_text(ncid, varid, start, edges, stride, imapp, (char *) value); break; case NC_BYTE: status = nc_get_varm_schar(ncid, varid, start, edges, stride, imapp, (schar *) value); break; case NC_SHORT: status = nc_get_varm_short(ncid, varid, start, edges, stride, imapp, (short *) value); break; case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) status = nc_get_varm_int(ncid, varid, start, edges, stride, imapp, (int *) value); #elif SIZEOF_LONG == X_SIZEOF_INT status = nc_get_varm_long(ncid, varid, start, edges, stride, imapp, (long *) value); #else #error "nc_get_varm implementation" #endif break; case NC_FLOAT: status = nc_get_varm_float(ncid, varid, start, edges, stride, imapp, (float *) value); break; case NC_DOUBLE: status = nc_get_varm_double(ncid, varid, start, edges, stride, imapp, (double *) value); break; default: status = NC_EBADTYPE; break; } if(cvtmap != NULL) { free(cvtmap); } return status; } int nc_put_varm ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const ptrdiff_t * imapp, const void *value) { int status; nc_type vartype; int varndims; ptrdiff_t *cvtmap = NULL; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; status = nc_inq_varndims(ncid, varid, &varndims); if(status != NC_NOERR) return status; if(imapp != NULL && varndims != 0) { /* * convert map units from bytes to units of sizeof(type) */ size_t ii; const ptrdiff_t szof = (ptrdiff_t) nctypelen(vartype); cvtmap = (ptrdiff_t *)calloc(varndims, sizeof(ptrdiff_t)); if(cvtmap == NULL) return NC_ENOMEM; for(ii = 0; (int)ii < varndims; ii++) { if(imapp[ii] % szof != 0) { free(cvtmap); return NC_EINVAL; } cvtmap[ii] = imapp[ii] / szof; } imapp = cvtmap; } switch(vartype){ case NC_CHAR: status = nc_put_varm_text(ncid, varid, start, edges, stride, imapp, (const char *) value); break; case NC_BYTE: status = nc_put_varm_schar(ncid, varid, start, edges, stride, imapp, (const schar *) value); break; case NC_SHORT: status = nc_put_varm_short(ncid, varid, start, edges, stride, imapp, (const short *) value); break; case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) status = nc_put_varm_int(ncid, varid, start, edges, stride, imapp, (const int *) value); #elif SIZEOF_LONG == X_SIZEOF_INT status = nc_put_varm_long(ncid, varid, start, edges, stride, imapp, (const long *) value); #else #error "nc_put_varm implementation" #endif break; case NC_FLOAT: status = nc_put_varm_float(ncid, varid, start, edges, stride, imapp, (const float *) value); break; case NC_DOUBLE: status = nc_put_varm_double(ncid, varid, start, edges, stride, imapp, (const double *) value); break; default: status = NC_EBADTYPE; break; } if(cvtmap != NULL) { free(cvtmap); } return status; } int nc_get_vars ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, void *value) { return nc_get_varm (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const void *value) { return nc_put_varm (ncid, varid, start, edges, stride, 0, value); } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/ncx.m40000644000175000017500000015631711606020250021527 0ustar amckinstryamckinstrydnl This is m4 source. dnl Process using m4 to produce 'C' language file. dnl dnl If you see this line, you can ignore the next one. /* Do not edit this file. It is produced from the corresponding .m4 source */ dnl /* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. * * This file contains some routines derived from code * which is copyrighted by Sun Microsystems, Inc. * The "#ifdef vax" versions of * ncx_put_float_float() * ncx_get_float_float() * ncx_put_double_double() * ncx_get_double_double() * ncx_putn_float_float() * ncx_getn_float_float() * ncx_putn_double_double() * ncx_getn_double_double() * are derived from xdr_float() and xdr_double() routines * in the freely available, copyrighted Sun RPCSRC 3.9 * distribution, xdr_float.c. * Our "value added" is that these are always memory to memory, * they handle IEEE subnormals properly, and their "n" versions * operate speedily on arrays. */ /* $Id: ncx.m4,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ /* * An external data representation interface. */ #include "ncx.h" #include #include /* alias poorly named limits.h macros */ #define SHORT_MAX SHRT_MAX #define SHORT_MIN SHRT_MIN #define USHORT_MAX USHRT_MAX #include #ifndef FLT_MAX /* This POSIX macro missing on some systems */ # ifndef NO_IEEE_FLOAT # define FLT_MAX 3.40282347e+38f # else # error "You will need to define FLT_MAX" # endif #endif #include /* * If the machine's float domain is "smaller" than the external one * use the machine domain */ #if defined(FLT_MAX_EXP) && FLT_MAX_EXP < 128 /* 128 is X_FLT_MAX_EXP */ #undef X_FLOAT_MAX # define X_FLOAT_MAX FLT_MAX #undef X_FLOAT_MIN # define X_FLOAT_MIN (-X_FLOAT_MAX) #endif #if _SX /* NEC SUPER UX */ #if _INT64 #undef INT_MAX /* workaround cpp bug */ #define INT_MAX X_INT_MAX #undef INT_MIN /* workaround cpp bug */ #define INT_MIN X_INT_MIN #undef LONG_MAX /* workaround cpp bug */ #define LONG_MAX X_INT_MAX #undef LONG_MIN /* workaround cpp bug */ #define LONG_MIN X_INT_MIN #elif _LONG64 #undef LONG_MAX /* workaround cpp bug */ #define LONG_MAX 4294967295L #undef LONG_MIN /* workaround cpp bug */ #define LONG_MIN -4294967295L #endif #endif /* _SX */ static const char nada[X_ALIGN] = {0, 0, 0, 0}; #ifndef WORDS_BIGENDIAN /* LITTLE_ENDIAN: DEC and intel */ /* * Routines to convert to BIGENDIAN. * Optimize the swapn?b() and swap?b() routines aggressivly. */ #define SWAP2(a) ( (((a) & 0xff) << 8) | \ (((a) >> 8) & 0xff) ) #define SWAP4(a) ( ((a) << 24) | \ (((a) << 8) & 0x00ff0000) | \ (((a) >> 8) & 0x0000ff00) | \ (((a) >> 24) & 0x000000ff) ) static void swapn2b(void *dst, const void *src, size_t nn) { char *op = dst; const char *ip = src; /* unroll the following to reduce loop overhead * * while(nn-- != 0) * { * *op++ = *(++ip); * *op++ = *(ip++ -1); * } */ while(nn > 3) { *op++ = *(++ip); *op++ = *(ip++ -1); *op++ = *(++ip); *op++ = *(ip++ -1); *op++ = *(++ip); *op++ = *(ip++ -1); *op++ = *(++ip); *op++ = *(ip++ -1); nn -= 4; } while(nn-- != 0) { *op++ = *(++ip); *op++ = *(ip++ -1); } } # ifndef vax static void swap4b(void *dst, const void *src) { char *op = dst; const char *ip = src; op[0] = ip[3]; op[1] = ip[2]; op[2] = ip[1]; op[3] = ip[0]; } # endif /* !vax */ static void swapn4b(void *dst, const void *src, size_t nn) { char *op = dst; const char *ip = src; /* unroll the following to reduce loop overhead * while(nn-- != 0) * { * op[0] = ip[3]; * op[1] = ip[2]; * op[2] = ip[1]; * op[3] = ip[0]; * op += 4; * ip += 4; * } */ while(nn > 3) { op[0] = ip[3]; op[1] = ip[2]; op[2] = ip[1]; op[3] = ip[0]; op[4] = ip[7]; op[5] = ip[6]; op[6] = ip[5]; op[7] = ip[4]; op[8] = ip[11]; op[9] = ip[10]; op[10] = ip[9]; op[11] = ip[8]; op[12] = ip[15]; op[13] = ip[14]; op[14] = ip[13]; op[15] = ip[12]; op += 16; ip += 16; nn -= 4; } while(nn-- != 0) { op[0] = ip[3]; op[1] = ip[2]; op[2] = ip[1]; op[3] = ip[0]; op += 4; ip += 4; } } # ifndef vax static void swap8b(void *dst, const void *src) { char *op = dst; const char *ip = src; op[0] = ip[7]; op[1] = ip[6]; op[2] = ip[5]; op[3] = ip[4]; op[4] = ip[3]; op[5] = ip[2]; op[6] = ip[1]; op[7] = ip[0]; } # endif /* !vax */ # ifndef vax static void swapn8b(void *dst, const void *src, size_t nn) { char *op = dst; const char *ip = src; /* unroll the following to reduce loop overhead * while(nn-- != 0) * { * op[0] = ip[7]; * op[1] = ip[6]; * op[2] = ip[5]; * op[3] = ip[4]; * op[4] = ip[3]; * op[5] = ip[2]; * op[6] = ip[1]; * op[7] = ip[0]; * op += 8; * ip += 8; * } */ while(nn > 1) { op[0] = ip[7]; op[1] = ip[6]; op[2] = ip[5]; op[3] = ip[4]; op[4] = ip[3]; op[5] = ip[2]; op[6] = ip[1]; op[7] = ip[0]; op[8] = ip[15]; op[9] = ip[14]; op[10] = ip[13]; op[11] = ip[12]; op[12] = ip[11]; op[13] = ip[10]; op[14] = ip[9]; op[15] = ip[8]; op += 16; ip += 16; nn -= 2; } while(nn-- != 0) { op[0] = ip[7]; op[1] = ip[6]; op[2] = ip[5]; op[3] = ip[4]; op[4] = ip[3]; op[5] = ip[2]; op[6] = ip[1]; op[7] = ip[0]; op += 8; ip += 8; } } # endif /* !vax */ #endif /* LITTLE_ENDIAN */ /* * Primitive numeric conversion functions. */ /* x_schar */ /* We don't implement and x_schar primitives. */ /* x_short */ #if SHORT_MAX == X_SHORT_MAX typedef short ix_short; #define SIZEOF_IX_SHORT SIZEOF_SHORT #define IX_SHORT_MAX SHORT_MAX #elif INT_MAX >= X_SHORT_MAX typedef int ix_short; #define SIZEOF_IX_SHORT SIZEOF_INT #define IX_SHORT_MAX INT_MAX #elif LONG_MAX >= X_SHORT_MAX typedef long ix_short; #define SIZEOF_IX_SHORT SIZEOF_LONG #define IX_SHORT_MAX LONG_MAX #else #error "ix_short implementation" #endif static void get_ix_short(const void *xp, ix_short *ip) { const uchar *cp = (const uchar *) xp; *ip = *cp++ << 8; #if SIZEOF_IX_SHORT > X_SIZEOF_SHORT if(*ip & 0x8000) { /* extern is negative */ *ip |= (~(0xffff)); /* N.B. Assumes "twos complement" */ } #endif *ip |= *cp; } static void put_ix_short(void *xp, const ix_short *ip) { uchar *cp = (uchar *) xp; *cp++ = (uchar)( (*ip) >> 8 ); *cp = (uchar)(*ip) & 0xff; } int ncx_get_short_schar(const void *xp, schar *ip) { ix_short xx; get_ix_short(xp, &xx); *ip = (schar)xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_short_uchar(const void *xp, uchar *ip) { ix_short xx; get_ix_short(xp, &xx); *ip = (uchar)xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_short_short(const void *xp, short *ip) { #if SIZEOF_IX_SHORT == SIZEOF_SHORT && IX_SHORT_MAX == SHORT_MAX get_ix_short(xp, (ix_short *)ip); return ENOERR; #else ix_short xx; get_ix_short(xp, &xx); *ip = xx; # if IX_SHORT_MAX > SHORT_MAX if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_short_int(const void *xp, int *ip) { #if SIZEOF_IX_SHORT == SIZEOF_INT && IX_SHORT_MAX == INT_MAX get_ix_short(xp, (ix_short *)ip); return ENOERR; #else ix_short xx; get_ix_short(xp, &xx); *ip = xx; # if IX_SHORT_MAX > INT_MAX if(xx > INT_MAX || xx < INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_short_long(const void *xp, long *ip) { #if SIZEOF_IX_SHORT == SIZEOF_LONG && IX_SHORT_MAX == LONG_MAX get_ix_short(xp, (ix_short *)ip); return ENOERR; #else /* assert(LONG_MAX >= X_SHORT_MAX); */ ix_short xx; get_ix_short(xp, &xx); *ip = xx; return ENOERR; #endif } int ncx_get_short_float(const void *xp, float *ip) { ix_short xx; get_ix_short(xp, &xx); *ip = xx; #if 0 /* TODO: determine when necessary */ if(xx > FLT_MAX || xx < (-FLT_MAX)) return NC_ERANGE; #endif return ENOERR; } int ncx_get_short_double(const void *xp, double *ip) { /* assert(DBL_MAX >= X_SHORT_MAX); */ ix_short xx; get_ix_short(xp, &xx); *ip = xx; return ENOERR; } int ncx_put_short_schar(void *xp, const schar *ip) { uchar *cp = (uchar *) xp; if(*ip & 0x80) *cp++ = 0xff; else *cp++ = 0; *cp = (uchar)*ip; return ENOERR; } int ncx_put_short_uchar(void *xp, const uchar *ip) { uchar *cp = (uchar *) xp; *cp++ = 0; *cp = *ip; return ENOERR; } int ncx_put_short_short(void *xp, const short *ip) { #if SIZEOF_IX_SHORT == SIZEOF_SHORT && X_SHORT_MAX == SHORT_MAX put_ix_short(xp, (const ix_short *)ip); return ENOERR; #else ix_short xx = (ix_short)*ip; put_ix_short(xp, &xx); # if X_SHORT_MAX < SHORT_MAX if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_short_int(void *xp, const int *ip) { #if SIZEOF_IX_SHORT == SIZEOF_INT && X_SHORT_MAX == INT_MAX put_ix_short(xp, (const ix_short *)ip); return ENOERR; #else ix_short xx = (ix_short)*ip; put_ix_short(xp, &xx); # if X_SHORT_MAX < INT_MAX if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_short_long(void *xp, const long *ip) { #if SIZEOF_IX_SHORT == SIZEOF_LONG && X_SHORT_MAX == LONG_MAX put_ix_short(xp, (const ix_short *)ip); return ENOERR; #else ix_short xx = (ix_short)*ip; put_ix_short(xp, &xx); # if X_SHORT_MAX < LONG_MAX if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_short_float(void *xp, const float *ip) { ix_short xx = (ix_short) *ip; put_ix_short(xp, &xx); if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; return ENOERR; } int ncx_put_short_double(void *xp, const double *ip) { ix_short xx = (ix_short) *ip; put_ix_short(xp, &xx); if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; return ENOERR; } /* x_int */ #if SHORT_MAX == X_INT_MAX typedef short ix_int; #define SIZEOF_IX_INT SIZEOF_SHORT #define IX_INT_MAX SHORT_MAX #elif INT_MAX >= X_INT_MAX typedef int ix_int; #define SIZEOF_IX_INT SIZEOF_INT #define IX_INT_MAX INT_MAX #elif LONG_MAX >= X_INT_MAX typedef long ix_int; #define SIZEOF_IX_INT SIZEOF_LONG #define IX_INT_MAX LONG_MAX #else #error "ix_int implementation" #endif static void get_ix_int(const void *xp, ix_int *ip) { const uchar *cp = (const uchar *) xp; *ip = *cp++ << 24; #if SIZEOF_IX_INT > X_SIZEOF_INT if(*ip & 0x80000000) { /* extern is negative */ *ip |= (~(0xffffffff)); /* N.B. Assumes "twos complement" */ } #endif *ip |= (*cp++ << 16); *ip |= (*cp++ << 8); *ip |= *cp; } static void put_ix_int(void *xp, const ix_int *ip) { uchar *cp = (uchar *) xp; *cp++ = (uchar)( (*ip) >> 24 ); *cp++ = (uchar)( ((*ip) & 0x00ff0000) >> 16 ); *cp++ = (uchar)( ((*ip) & 0x0000ff00) >> 8 ); *cp = (uchar) ((*ip) & 0x000000ff); } int ncx_get_int_schar(const void *xp, schar *ip) { ix_int xx; get_ix_int(xp, &xx); *ip = (schar)xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_int_uchar(const void *xp, uchar *ip) { ix_int xx; get_ix_int(xp, &xx); *ip = (uchar)xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_int_short(const void *xp, short *ip) { #if SIZEOF_IX_INT == SIZEOF_SHORT && IX_INT_MAX == SHORT_MAX get_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx; get_ix_int(xp, &xx); *ip = (short)xx; # if IX_INT_MAX > SHORT_MAX if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_int_int(const void *xp, int *ip) { #if SIZEOF_IX_INT == SIZEOF_INT && IX_INT_MAX == INT_MAX get_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx; get_ix_int(xp, &xx); *ip = xx; # if IX_INT_MAX > INT_MAX if(xx > INT_MAX || xx < INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_int_long(const void *xp, long *ip) { #if SIZEOF_IX_INT == SIZEOF_LONG && IX_INT_MAX == LONG_MAX get_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx; get_ix_int(xp, &xx); *ip = xx; # if IX_INT_MAX > LONG_MAX /* unlikely */ if(xx > LONG_MAX || xx < LONG_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_int_float(const void *xp, float *ip) { ix_int xx; get_ix_int(xp, &xx); *ip = (float)xx; #if 0 /* TODO: determine when necessary */ if(xx > FLT_MAX || xx < (-FLT_MAX)) return NC_ERANGE; #endif return ENOERR; } int ncx_get_int_double(const void *xp, double *ip) { /* assert((DBL_MAX >= X_INT_MAX); */ ix_int xx; get_ix_int(xp, &xx); *ip = xx; return ENOERR; } int ncx_put_int_schar(void *xp, const schar *ip) { uchar *cp = (uchar *) xp; if(*ip & 0x80) { *cp++ = 0xff; *cp++ = 0xff; *cp++ = 0xff; } else { *cp++ = 0x00; *cp++ = 0x00; *cp++ = 0x00; } *cp = (uchar)*ip; return ENOERR; } int ncx_put_int_uchar(void *xp, const uchar *ip) { uchar *cp = (uchar *) xp; *cp++ = 0x00; *cp++ = 0x00; *cp++ = 0x00; *cp = *ip; return ENOERR; } int ncx_put_int_short(void *xp, const short *ip) { #if SIZEOF_IX_INT == SIZEOF_SHORT && IX_INT_MAX == SHORT_MAX put_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); # if IX_INT_MAX < SHORT_MAX if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_int_int(void *xp, const int *ip) { #if SIZEOF_IX_INT == SIZEOF_INT && IX_INT_MAX == INT_MAX put_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); # if IX_INT_MAX < INT_MAX if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_int_long(void *xp, const long *ip) { #if SIZEOF_IX_INT == SIZEOF_LONG && IX_INT_MAX == LONG_MAX put_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); # if IX_INT_MAX < LONG_MAX if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_int_float(void *xp, const float *ip) { ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); if(*ip > (double)X_INT_MAX || *ip < (double)X_INT_MIN) return NC_ERANGE; return ENOERR; } int ncx_put_int_double(void *xp, const double *ip) { ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; return ENOERR; } /* x_float */ #if X_SIZEOF_FLOAT == SIZEOF_FLOAT && !defined(NO_IEEE_FLOAT) static void get_ix_float(const void *xp, float *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(ip, xp, sizeof(float)); #else swap4b(ip, xp); #endif } static void put_ix_float(void *xp, const float *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(xp, ip, X_SIZEOF_FLOAT); #else swap4b(xp, ip); #endif } #elif vax /* What IEEE single precision floating point looks like on a Vax */ struct ieee_single { unsigned int exp_hi : 7; unsigned int sign : 1; unsigned int mant_hi : 7; unsigned int exp_lo : 1; unsigned int mant_lo_hi : 8; unsigned int mant_lo_lo : 8; }; /* Vax single precision floating point */ struct vax_single { unsigned int mantissa1 : 7; unsigned int exp : 8; unsigned int sign : 1; unsigned int mantissa2 : 16; }; #define VAX_SNG_BIAS 0x81 #define IEEE_SNG_BIAS 0x7f static struct sgl_limits { struct vax_single s; struct ieee_single ieee; } max = { { 0x7f, 0xff, 0x0, 0xffff }, /* Max Vax */ { 0x7f, 0x0, 0x0, 0x1, 0x0, 0x0 } /* Max IEEE */ }; static struct sgl_limits min = { { 0x0, 0x0, 0x0, 0x0 }, /* Min Vax */ { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } /* Min IEEE */ }; dnl dnl dnl dnl dnl GET_VAX_DFLOAT_Body(xp) (body for get_ix_float) dnl define(`GET_VAX_DFLOAT_Body',dnl `dnl struct vax_single *const vsp = (struct vax_single *) ip; const struct ieee_single *const isp = (const struct ieee_single *) $1; unsigned exp = isp->exp_hi << 1 | isp->exp_lo; switch(exp) { case 0 : /* ieee subnormal */ if(isp->mant_hi == min.ieee.mant_hi && isp->mant_lo_hi == min.ieee.mant_lo_hi && isp->mant_lo_lo == min.ieee.mant_lo_lo) { *vsp = min.s; } else { unsigned mantissa = (isp->mant_hi << 16) | isp->mant_lo_hi << 8 | isp->mant_lo_lo; unsigned tmp = mantissa >> 20; if(tmp >= 4) { vsp->exp = 2; } else if (tmp >= 2) { vsp->exp = 1; } else { *vsp = min.s; break; } /* else */ tmp = mantissa - (1 << (20 + vsp->exp )); tmp <<= 3 - vsp->exp; vsp->mantissa2 = tmp; vsp->mantissa1 = (tmp >> 16); } break; case 0xfe : case 0xff : *vsp = max.s; break; default : vsp->exp = exp - IEEE_SNG_BIAS + VAX_SNG_BIAS; vsp->mantissa2 = isp->mant_lo_hi << 8 | isp->mant_lo_lo; vsp->mantissa1 = isp->mant_hi; } vsp->sign = isp->sign; ')dnl static void get_ix_float(const void *xp, float *ip) { GET_VAX_DFLOAT_Body(xp) } dnl dnl dnl dnl dnl PUT_VAX_DFLOAT_Body(xp) (body for get_ix_float) dnl define(`PUT_VAX_DFLOAT_Body',dnl `dnl const struct vax_single *const vsp = (const struct vax_single *)ip; struct ieee_single *const isp = (struct ieee_single *) $1; switch(vsp->exp){ case 0 : /* all vax float with zero exponent map to zero */ *isp = min.ieee; break; case 2 : case 1 : { /* These will map to subnormals */ unsigned mantissa = (vsp->mantissa1 << 16) | vsp->mantissa2; mantissa >>= 3 - vsp->exp; mantissa += (1 << (20 + vsp->exp)); isp->mant_lo_lo = mantissa; isp->mant_lo_hi = mantissa >> 8; isp->mant_hi = mantissa >> 16; isp->exp_lo = 0; isp->exp_hi = 0; } break; case 0xff : /* max.s.exp */ if( vsp->mantissa2 == max.s.mantissa2 && vsp->mantissa1 == max.s.mantissa1) { /* map largest vax float to ieee infinity */ *isp = max.ieee; break; } /* else, fall thru */ default : { unsigned exp = vsp->exp - VAX_SNG_BIAS + IEEE_SNG_BIAS; isp->exp_hi = exp >> 1; isp->exp_lo = exp; isp->mant_lo_lo = vsp->mantissa2; isp->mant_lo_hi = vsp->mantissa2 >> 8; isp->mant_hi = vsp->mantissa1; } } isp->sign = vsp->sign; ')dnl static void put_ix_float(void *xp, const float *ip) { PUT_VAX_DFLOAT_Body(xp) } /* vax */ #elif defined(_CRAY) && !defined(__crayx1) /* * Return the number of bytes until the next "word" boundary * N.B. This is based on the very wierd YMP address structure, * which puts the address within a word in the leftmost 3 bits * of the address. */ static size_t word_align(const void *vp) { const size_t rem = ((size_t)vp >> (64 - 3)) & 0x7; return (rem != 0); } struct ieee_single_hi { unsigned int sign : 1; unsigned int exp : 8; unsigned int mant :23; unsigned int pad :32; }; typedef struct ieee_single_hi ieee_single_hi; struct ieee_single_lo { unsigned int pad :32; unsigned int sign : 1; unsigned int exp : 8; unsigned int mant :23; }; typedef struct ieee_single_lo ieee_single_lo; static const int ieee_single_bias = 0x7f; struct ieee_double { unsigned int sign : 1; unsigned int exp :11; unsigned int mant :52; }; typedef struct ieee_double ieee_double; static const int ieee_double_bias = 0x3ff; #if defined(NO_IEEE_FLOAT) struct cray_single { unsigned int sign : 1; unsigned int exp :15; unsigned int mant :48; }; typedef struct cray_single cray_single; static const int cs_ieis_bias = 0x4000 - 0x7f; static const int cs_id_bias = 0x4000 - 0x3ff; dnl dnl dnl dnl dnl GET_IX_FLOAT_Body (body for get_ix_float) dnl define(`GET_IX_FLOAT_Body',dnl `dnl cray_single *csp = (cray_single *) ip; if(isp->exp == 0) { /* ieee subnormal */ *ip = (double)isp->mant; if(isp->mant != 0) { csp->exp -= (ieee_single_bias + 22); } } else { csp->exp = isp->exp + cs_ieis_bias + 1; csp->mant = isp->mant << (48 - 1 - 23); csp->mant |= (1 << (48 - 1)); } csp->sign = isp->sign; ')dnl dnl dnl dnl dnl dnl PUT_IX_FLOAT_Body (body for put_ix_float) dnl define(`PUT_IX_FLOAT_Body',dnl `dnl const cray_single *csp = (const cray_single *) ip; int ieee_exp = csp->exp - cs_ieis_bias -1; isp->sign = csp->sign; if(ieee_exp >= 0xff) { /* NC_ERANGE => ieee Inf */ isp->exp = 0xff; isp->mant = 0x0; } else if(ieee_exp > 0) { /* normal ieee representation */ isp->exp = ieee_exp; /* assumes cray rep is in normal form */ assert(csp->mant & 0x800000000000); isp->mant = (((csp->mant << 1) & 0xffffffffffff) >> (48 - 23)); } else if(ieee_exp > -23) { /* ieee subnormal, right shift */ const int rshift = (48 - 23 - ieee_exp); isp->mant = csp->mant >> rshift; #if 0 if(csp->mant & (1 << (rshift -1))) { /* round up */ isp->mant++; } #endif isp->exp = 0; } else { /* smaller than ieee can represent */ isp->exp = 0; isp->mant = 0; } ')dnl static void get_ix_float(const void *xp, float *ip) { if(word_align(xp) == 0) { const ieee_single_hi *isp = (const ieee_single_hi *) xp; GET_IX_FLOAT_Body } else { const ieee_single_lo *isp = (const ieee_single_lo *) xp; GET_IX_FLOAT_Body } } static void put_ix_float(void *xp, const float *ip) { if(word_align(xp) == 0) { ieee_single_hi *isp = (ieee_single_hi*)xp; PUT_IX_FLOAT_Body } else { ieee_single_lo *isp = (ieee_single_lo*)xp; PUT_IX_FLOAT_Body } } #else /* IEEE Cray with only doubles */ static void get_ix_float(const void *xp, float *ip) { ieee_double *idp = (ieee_double *) ip; if(word_align(xp) == 0) { const ieee_single_hi *isp = (const ieee_single_hi *) xp; if(isp->exp == 0 && isp->mant == 0) { idp->exp = 0; idp->mant = 0; } else { idp->exp = isp->exp + (ieee_double_bias - ieee_single_bias); idp->mant = isp->mant << (52 - 23); } idp->sign = isp->sign; } else { const ieee_single_lo *isp = (const ieee_single_lo *) xp; if(isp->exp == 0 && isp->mant == 0) { idp->exp = 0; idp->mant = 0; } else { idp->exp = isp->exp + (ieee_double_bias - ieee_single_bias); idp->mant = isp->mant << (52 - 23); } idp->sign = isp->sign; } } static void put_ix_float(void *xp, const float *ip) { const ieee_double *idp = (const ieee_double *) ip; if(word_align(xp) == 0) { ieee_single_hi *isp = (ieee_single_hi*)xp; if(idp->exp > (ieee_double_bias - ieee_single_bias)) isp->exp = idp->exp - (ieee_double_bias - ieee_single_bias); else isp->exp = 0; isp->mant = idp->mant >> (52 - 23); isp->sign = idp->sign; } else { ieee_single_lo *isp = (ieee_single_lo*)xp; if(idp->exp > (ieee_double_bias - ieee_single_bias)) isp->exp = idp->exp - (ieee_double_bias - ieee_single_bias); else isp->exp = 0; isp->mant = idp->mant >> (52 - 23); isp->sign = idp->sign; } } #endif #elif _SX && _FLOAT2 static void get_ix_float(const void *xp, float *ip) { const int ncnv = ie3_fl2(xp, ip, 4, 8, 1); } static void put_ix_float(void *xp, const float *ip) { const int ncnv = fl2_ie3(ip, xp, 8, 4, 1); } #else #error "ix_float implementation" #endif int ncx_get_float_schar(const void *xp, schar *ip) { float xx; get_ix_float(xp, &xx); *ip = (schar) xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_uchar(const void *xp, uchar *ip) { float xx; get_ix_float(xp, &xx); *ip = (uchar) xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_float_short(const void *xp, short *ip) { float xx; get_ix_float(xp, &xx); *ip = (short) xx; if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_int(const void *xp, int *ip) { float xx; get_ix_float(xp, &xx); *ip = (int) xx; if(xx > (double)INT_MAX || xx < (double)INT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_long(const void *xp, long *ip) { float xx; get_ix_float(xp, &xx); *ip = (long) xx; if(xx > LONG_MAX || xx < LONG_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_float(const void *xp, float *ip) { /* TODO */ get_ix_float(xp, ip); return ENOERR; } int ncx_get_float_double(const void *xp, double *ip) { /* TODO */ float xx; get_ix_float(xp, &xx); *ip = xx; return ENOERR; } int ncx_put_float_schar(void *xp, const schar *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); return ENOERR; } int ncx_put_float_uchar(void *xp, const uchar *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); return ENOERR; } int ncx_put_float_short(void *xp, const short *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); #if 0 /* TODO: figure this out */ if((float)(*ip) > X_FLOAT_MAX || (float)(*ip) < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_int(void *xp, const int *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); #if 1 /* TODO: figure this out */ if((float)(*ip) > X_FLOAT_MAX || (float)(*ip) < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_long(void *xp, const long *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); #if 1 /* TODO: figure this out */ if((float)(*ip) > X_FLOAT_MAX || (float)(*ip) < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_float(void *xp, const float *ip) { put_ix_float(xp, ip); #ifdef NO_IEEE_FLOAT if(*ip > X_FLOAT_MAX || *ip < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_double(void *xp, const double *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); if(*ip > X_FLOAT_MAX || *ip < X_FLOAT_MIN) return NC_ERANGE; return ENOERR; } /* x_double */ #if X_SIZEOF_DOUBLE == SIZEOF_DOUBLE && !defined(NO_IEEE_FLOAT) static void get_ix_double(const void *xp, double *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(ip, xp, sizeof(double)); #else swap8b(ip, xp); #endif } static void put_ix_double(void *xp, const double *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(xp, ip, X_SIZEOF_DOUBLE); #else swap8b(xp, ip); #endif } #elif vax /* What IEEE double precision floating point looks like on a Vax */ struct ieee_double { unsigned int exp_hi : 7; unsigned int sign : 1; unsigned int mant_6 : 4; unsigned int exp_lo : 4; unsigned int mant_5 : 8; unsigned int mant_4 : 8; unsigned int mant_lo : 32; }; /* Vax double precision floating point */ struct vax_double { unsigned int mantissa1 : 7; unsigned int exp : 8; unsigned int sign : 1; unsigned int mantissa2 : 16; unsigned int mantissa3 : 16; unsigned int mantissa4 : 16; }; #define VAX_DBL_BIAS 0x81 #define IEEE_DBL_BIAS 0x3ff #define MASK(nbits) ((1 << nbits) - 1) static const struct dbl_limits { struct vax_double d; struct ieee_double ieee; } dbl_limits[2] = { {{ 0x7f, 0xff, 0x0, 0xffff, 0xffff, 0xffff }, /* Max Vax */ { 0x7f, 0x0, 0x0, 0xf, 0x0, 0x0, 0x0}}, /* Max IEEE */ {{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, /* Min Vax */ { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}}, /* Min IEEE */ }; dnl dnl dnl dnl dnl GET_VAX_DDOUBLE_Body(xp) (body for get_ix_double) dnl define(`GET_VAX_DDOUBLE_Body',dnl `dnl struct vax_double *const vdp = (struct vax_double *)ip; const struct ieee_double *const idp = (const struct ieee_double *) $1; { const struct dbl_limits *lim; int ii; for (ii = 0, lim = dbl_limits; ii < sizeof(dbl_limits)/sizeof(struct dbl_limits); ii++, lim++) { if ((idp->mant_lo == lim->ieee.mant_lo) && (idp->mant_4 == lim->ieee.mant_4) && (idp->mant_5 == lim->ieee.mant_5) && (idp->mant_6 == lim->ieee.mant_6) && (idp->exp_lo == lim->ieee.exp_lo) && (idp->exp_hi == lim->ieee.exp_hi) ) { *vdp = lim->d; goto doneit; } } } { unsigned exp = idp->exp_hi << 4 | idp->exp_lo; vdp->exp = exp - IEEE_DBL_BIAS + VAX_DBL_BIAS; } { unsigned mant_hi = ((idp->mant_6 << 16) | (idp->mant_5 << 8) | idp->mant_4); unsigned mant_lo = SWAP4(idp->mant_lo); vdp->mantissa1 = (mant_hi >> 13); vdp->mantissa2 = ((mant_hi & MASK(13)) << 3) | (mant_lo >> 29); vdp->mantissa3 = (mant_lo >> 13); vdp->mantissa4 = (mant_lo << 3); } doneit: vdp->sign = idp->sign; ')dnl static void get_ix_double(const void *xp, double *ip) { GET_VAX_DDOUBLE_Body(xp) } dnl dnl dnl dnl dnl PUT_VAX_DDOUBLE_Body(xp) (body for put_ix_double) dnl define(`PUT_VAX_DDOUBLE_Body',dnl `dnl const struct vax_double *const vdp = (const struct vax_double *)ip; struct ieee_double *const idp = (struct ieee_double *) $1; if ((vdp->mantissa4 > (dbl_limits[0].d.mantissa4 - 3)) && (vdp->mantissa3 == dbl_limits[0].d.mantissa3) && (vdp->mantissa2 == dbl_limits[0].d.mantissa2) && (vdp->mantissa1 == dbl_limits[0].d.mantissa1) && (vdp->exp == dbl_limits[0].d.exp)) { *idp = dbl_limits[0].ieee; goto shipit; } if ((vdp->mantissa4 == dbl_limits[1].d.mantissa4) && (vdp->mantissa3 == dbl_limits[1].d.mantissa3) && (vdp->mantissa2 == dbl_limits[1].d.mantissa2) && (vdp->mantissa1 == dbl_limits[1].d.mantissa1) && (vdp->exp == dbl_limits[1].d.exp)) { *idp = dbl_limits[1].ieee; goto shipit; } { unsigned exp = vdp->exp - VAX_DBL_BIAS + IEEE_DBL_BIAS; unsigned mant_lo = ((vdp->mantissa2 & MASK(3)) << 29) | (vdp->mantissa3 << 13) | ((vdp->mantissa4 >> 3) & MASK(13)); unsigned mant_hi = (vdp->mantissa1 << 13) | (vdp->mantissa2 >> 3); if((vdp->mantissa4 & 7) > 4) { /* round up */ mant_lo++; if(mant_lo == 0) { mant_hi++; if(mant_hi > 0xffffff) { mant_hi = 0; exp++; } } } idp->mant_lo = SWAP4(mant_lo); idp->mant_6 = mant_hi >> 16; idp->mant_5 = (mant_hi & 0xff00) >> 8; idp->mant_4 = mant_hi; idp->exp_hi = exp >> 4; idp->exp_lo = exp; } shipit: idp->sign = vdp->sign; ')dnl static void put_ix_double(void *xp, const double *ip) { PUT_VAX_DDOUBLE_Body(xp) } /* vax */ #elif defined(_CRAY) && !defined(__crayx1) static void get_ix_double(const void *xp, double *ip) { const ieee_double *idp = (const ieee_double *) xp; cray_single *csp = (cray_single *) ip; if(idp->exp == 0) { /* ieee subnormal */ *ip = (double)idp->mant; if(idp->mant != 0) { csp->exp -= (ieee_double_bias + 51); } } else { csp->exp = idp->exp + cs_id_bias + 1; csp->mant = idp->mant >> (52 - 48 + 1); csp->mant |= (1 << (48 - 1)); } csp->sign = idp->sign; } static void put_ix_double(void *xp, const double *ip) { ieee_double *idp = (ieee_double *) xp; const cray_single *csp = (const cray_single *) ip; int ieee_exp = csp->exp - cs_id_bias -1; idp->sign = csp->sign; if(ieee_exp >= 0x7ff) { /* NC_ERANGE => ieee Inf */ idp->exp = 0x7ff; idp->mant = 0x0; } else if(ieee_exp > 0) { /* normal ieee representation */ idp->exp = ieee_exp; /* assumes cray rep is in normal form */ assert(csp->mant & 0x800000000000); idp->mant = (((csp->mant << 1) & 0xffffffffffff) << (52 - 48)); } else if(ieee_exp >= (-(52 -48))) { /* ieee subnormal, left shift */ const int lshift = (52 - 48) + ieee_exp; idp->mant = csp->mant << lshift; idp->exp = 0; } else if(ieee_exp >= -52) { /* ieee subnormal, right shift */ const int rshift = (- (52 - 48) - ieee_exp); idp->mant = csp->mant >> rshift; #if 0 if(csp->mant & (1 << (rshift -1))) { /* round up */ idp->mant++; } #endif idp->exp = 0; } else { /* smaller than ieee can represent */ idp->exp = 0; idp->mant = 0; } } #elif _SX && _FLOAT2 static void get_ix_double(const void *xp, double *ip) { const int ncnv = ie3_fl2(xp, ip, 8, 8, 1); } static void put_ix_double(void *xp, const double *ip) { const int ncnv = fl2_ie3(ip, xp, 8, 8, 1); } #else #error "ix_double implementation" #endif int ncx_get_double_schar(const void *xp, schar *ip) { double xx; get_ix_double(xp, &xx); *ip = (schar) xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_uchar(const void *xp, uchar *ip) { double xx; get_ix_double(xp, &xx); *ip = (uchar) xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_double_short(const void *xp, short *ip) { double xx; get_ix_double(xp, &xx); *ip = (short) xx; if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_int(const void *xp, int *ip) { double xx; get_ix_double(xp, &xx); *ip = (int) xx; if(xx > INT_MAX || xx < INT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_long(const void *xp, long *ip) { double xx; get_ix_double(xp, &xx); *ip = (long) xx; if(xx > LONG_MAX || xx < LONG_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_float(const void *xp, float *ip) { double xx; get_ix_double(xp, &xx); if(xx > FLT_MAX || xx < (-FLT_MAX)) { *ip = FLT_MAX; return NC_ERANGE; } if(xx < (-FLT_MAX)) { *ip = (-FLT_MAX); return NC_ERANGE; } *ip = (float) xx; return ENOERR; } int ncx_get_double_double(const void *xp, double *ip) { /* TODO */ get_ix_double(xp, ip); return ENOERR; } int ncx_put_double_schar(void *xp, const schar *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); return ENOERR; } int ncx_put_double_uchar(void *xp, const uchar *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); return ENOERR; } int ncx_put_double_short(void *xp, const short *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 0 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_int(void *xp, const int *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 0 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_long(void *xp, const long *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 1 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_float(void *xp, const float *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 1 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_double(void *xp, const double *ip) { put_ix_double(xp, ip); #ifdef NO_IEEE_FLOAT if(*ip > X_DOUBLE_MAX || *ip < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } /* x_size_t */ #if SIZEOF_SIZE_T < X_SIZEOF_SIZE_T #error "x_size_t implementation" /* netcdf requires size_t which can hold values from 0 to 2^32 -1 */ #endif int ncx_put_size_t(void **xpp, const size_t *ulp) { /* similar to put_ix_int() */ uchar *cp = (uchar *) *xpp; #if SIZEOF_SIZE_T != X_SIZEOF_INT assert(*ulp <= X_SIZE_MAX); #endif *cp++ = (uchar)((*ulp) >> 24); *cp++ = (uchar)(((*ulp) & 0x00ff0000) >> 16); *cp++ = (uchar)(((*ulp) & 0x0000ff00) >> 8); *cp = (uchar)((*ulp) & 0x000000ff); *xpp = (void *)((char *)(*xpp) + X_SIZEOF_SIZE_T); return ENOERR; } int ncx_get_size_t(const void **xpp, size_t *ulp) { /* similar to get_ix_int */ const uchar *cp = (const uchar *) *xpp; *ulp = (unsigned)(*cp++ << 24); *ulp |= (*cp++ << 16); *ulp |= (*cp++ << 8); *ulp |= *cp; *xpp = (const void *)((const char *)(*xpp) + X_SIZEOF_SIZE_T); return ENOERR; } /* x_off_t */ int ncx_put_off_t(void **xpp, const off_t *lp, size_t sizeof_off_t) { /* similar to put_ix_int() */ uchar *cp = (uchar *) *xpp; /* No negative offsets stored in netcdf */ if (*lp < 0) { /* Assume this is an overflow of a 32-bit int... */ return ERANGE; } assert(sizeof_off_t == 4 || sizeof_off_t == 8); if (sizeof_off_t == 4) { *cp++ = (uchar) ((*lp) >> 24); *cp++ = (uchar)(((*lp) & 0x00ff0000) >> 16); *cp++ = (uchar)(((*lp) & 0x0000ff00) >> 8); *cp = (uchar)( (*lp) & 0x000000ff); } else { #if SIZEOF_OFF_T == 4 /* Write a 64-bit offset on a system with only a 32-bit offset */ *cp++ = (uchar)0; *cp++ = (uchar)0; *cp++ = (uchar)0; *cp++ = (uchar)0; *cp++ = (uchar)(((*lp) & 0xff000000) >> 24); *cp++ = (uchar)(((*lp) & 0x00ff0000) >> 16); *cp++ = (uchar)(((*lp) & 0x0000ff00) >> 8); *cp = (uchar)( (*lp) & 0x000000ff); #else *cp++ = (uchar) ((*lp) >> 56); *cp++ = (uchar)(((*lp) & 0x00ff000000000000ULL) >> 48); *cp++ = (uchar)(((*lp) & 0x0000ff0000000000ULL) >> 40); *cp++ = (uchar)(((*lp) & 0x000000ff00000000ULL) >> 32); *cp++ = (uchar)(((*lp) & 0x00000000ff000000ULL) >> 24); *cp++ = (uchar)(((*lp) & 0x0000000000ff0000ULL) >> 16); *cp++ = (uchar)(((*lp) & 0x000000000000ff00ULL) >> 8); *cp = (uchar)( (*lp) & 0x00000000000000ffULL); #endif } *xpp = (void *)((char *)(*xpp) + sizeof_off_t); return ENOERR; } int ncx_get_off_t(const void **xpp, off_t *lp, size_t sizeof_off_t) { /* similar to get_ix_int() */ const uchar *cp = (const uchar *) *xpp; assert(sizeof_off_t == 4 || sizeof_off_t == 8); if (sizeof_off_t == 4) { *lp = *cp++ << 24; *lp |= (*cp++ << 16); *lp |= (*cp++ << 8); *lp |= *cp; } else { #if SIZEOF_OFF_T == 4 /* Read a 64-bit offset on a system with only a 32-bit offset */ /* If the offset overflows, set an error code and return */ *lp = ((off_t)(*cp++) << 24); *lp |= ((off_t)(*cp++) << 16); *lp |= ((off_t)(*cp++) << 8); *lp |= ((off_t)(*cp++)); /* * lp now contains the upper 32-bits of the 64-bit offset. if lp is * not zero, then the dataset is larger than can be represented * on this system. Set an error code and return. */ if (*lp != 0) { return ERANGE; } *lp = ((off_t)(*cp++) << 24); *lp |= ((off_t)(*cp++) << 16); *lp |= ((off_t)(*cp++) << 8); *lp |= (off_t)*cp; if (*lp < 0) { /* * If this fails, then the offset is >2^31, but less * than 2^32 which is not allowed, but is not caught * by the previous check */ return ERANGE; } #else *lp = ((off_t)(*cp++) << 56); *lp |= ((off_t)(*cp++) << 48); *lp |= ((off_t)(*cp++) << 40); *lp |= ((off_t)(*cp++) << 32); *lp |= ((off_t)(*cp++) << 24); *lp |= ((off_t)(*cp++) << 16); *lp |= ((off_t)(*cp++) << 8); *lp |= (off_t)*cp; #endif } *xpp = (const void *)((const char *)(*xpp) + sizeof_off_t); return ENOERR; } /* * Aggregate numeric conversion functions. */ dnl dnl dnl dnl dnl Upcase(str) dnl define(`Upcase',dnl `dnl translit($1, abcdefghijklmnopqrstuvwxyz, ABCDEFGHIJKLMNOPQRSTUVWXYZ)')dnl dnl dnl dnl dnl dnl Xsizeof(Xtype) dnl define(`Xsizeof', ``X_SIZEOF_'Upcase($1)')dnl dnl dnl dnl dnl dnl dnl NCX_GETN_Byte_Body (body for one byte types on diagonal) dnl define(`NCX_GETN_Byte_Body',dnl `dnl (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; ')dnl dnl dnl dnl dnl dnl NCX_PAD_GETN_Byte_body (body for one byte types on diagonal) dnl define(`NCX_PAD_GETN_Byte_Body',dnl `dnl size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems + rndup); return ENOERR; ')dnl dnl dnl dnl dnl dnl NCX_GETN_SCHAR(Type) dnl define(`NCX_GETN_SCHAR',dnl `dnl int ncx_getn_schar_$1(const void **xpp, size_t nelems, $1 *tp) { schar *xp = (schar *)(*xpp); while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (const void *)xp; return ENOERR; } ')dnl dnl dnl dnl dnl dnl NCX_PAD_GETN_SCHAR(Type) dnl define(`NCX_PAD_GETN_SCHAR',dnl `dnl int ncx_pad_getn_schar_$1(const void **xpp, size_t nelems, $1 *tp) { size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (void *)(xp + rndup); return ENOERR; } ')dnl dnl dnl dnl dnl dnl NCX_GETNo(XType, Type) deprecated dnl define(`NCX_GETNo',dnl `dnl int ncx_getn_$1_$2(const void **xpp, size_t nelems, $2 *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; $1 xx; for( ; nelems != 0; nelems--, xp += Xsizeof($1), tp++) { const int lstatus = ncx_get_$1_$1(xp, &xx); *tp = ($2)xx; if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl NCX_GETN(XType, Type) dnl define(`NCX_GETN',dnl `dnl int ncx_getn_$1_$2(const void **xpp, size_t nelems, $2 *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += Xsizeof($1), tp++) { const int lstatus = ncx_get_$1_$2(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl NCX_PAD_GETN_SHORT( Type) dnl define(`NCX_PAD_GETN_SHORT',dnl `dnl int ncx_pad_getn_short_$1(const void **xpp, size_t nelems, $1 *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_$1(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl NCX_PUTN_Byte_Body(Type) (body for one byte types) dnl define(`NCX_PUTN_Byte_Body',dnl `dnl (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; ')dnl dnl dnl dnl dnl dnl NCX_PAD_PUTN_Byte_Body(Type) (body for one byte types) dnl define(`NCX_PAD_PUTN_Byte_Body',dnl size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); if(rndup) { (void) memcpy(*xpp, nada, rndup); *xpp = (void *)((char *)(*xpp) + rndup); } return ENOERR; `dnl ')dnl dnl dnl dnl dnl dnl NCX_PUTN_SCHAR(Type) dnl define(`NCX_PUTN_SCHAR',dnl `dnl int ncx_putn_schar_$1(void **xpp, size_t nelems, const $1 *tp) { int status = ENOERR; schar *xp = (schar *) *xpp; while(nelems-- != 0) { if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } *xpp = (void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl NCX_PAD_PUTN_SCHAR(Type) dnl define(`NCX_PAD_PUTN_SCHAR',dnl `dnl int ncx_pad_putn_schar_$1(void **xpp, size_t nelems, const $1 *tp) { int status = ENOERR; size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { /* N.B. schar as signed */ if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } if(rndup) { (void) memcpy(xp, nada, rndup); xp += rndup; } *xpp = (void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl NCX_PUTNo(XType, Type) deprecated dnl define(`NCX_PUTNo',dnl `dnl int ncx_putn_$1_$2(void **xpp, size_t nelems, const $2 *tp) { char *xp = (char *) *xpp; int status = ENOERR; $1 xx; for( ; nelems != 0; nelems--, xp += Xsizeof($1), tp++) { xx = ($1) *tp; { int lstatus = ncx_put_$1_$1(xp, &xx); if(lstatus != ENOERR) status = lstatus; } } *xpp = (void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl NCX_PUTN(XType, Type) dnl define(`NCX_PUTN',dnl `dnl int ncx_putn_$1_$2(void **xpp, size_t nelems, const $2 *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += Xsizeof($1), tp++) { int lstatus = ncx_put_$1_$2(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl NCX_PAD_PUTN_SHORT(Type) dnl define(`NCX_PAD_PUTN_SHORT',dnl `dnl int ncx_pad_putn_short_$1(void **xpp, size_t nelems, const $1 *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += Xsizeof(short), tp++) { int lstatus = ncx_put_short_$1(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } ')dnl dnl dnl dnl dnl dnl Declare & define routines dnl dnl dnl dnl /* schar */ dnl NCX_GETN_SCHAR(schar) int ncx_getn_schar_schar(const void **xpp, size_t nelems, schar *tp) { NCX_GETN_Byte_Body } dnl NCX_GETN_SCHAR(uchar) int ncx_getn_schar_uchar(const void **xpp, size_t nelems, uchar *tp) { NCX_GETN_Byte_Body } NCX_GETN_SCHAR(short) NCX_GETN_SCHAR(int) NCX_GETN_SCHAR(long) NCX_GETN_SCHAR(float) NCX_GETN_SCHAR(double) dnl NCX_PAD_GETN_SCHAR(schar) int ncx_pad_getn_schar_schar(const void **xpp, size_t nelems, schar *tp) { NCX_PAD_GETN_Byte_Body } dnl NCX_PAD_GETN_SCHAR(uchar) int ncx_pad_getn_schar_uchar(const void **xpp, size_t nelems, uchar *tp) { NCX_PAD_GETN_Byte_Body } NCX_PAD_GETN_SCHAR(short) NCX_PAD_GETN_SCHAR(int) NCX_PAD_GETN_SCHAR(long) NCX_PAD_GETN_SCHAR(float) NCX_PAD_GETN_SCHAR(double) dnl NCX_PUTN_SCHAR(schar) int ncx_putn_schar_schar(void **xpp, size_t nelems, const schar *tp) { NCX_PUTN_Byte_Body } dnl NCX_PUTN_SCHAR(uchar) int ncx_putn_schar_uchar(void **xpp, size_t nelems, const uchar *tp) { NCX_PUTN_Byte_Body } NCX_PUTN_SCHAR(short) NCX_PUTN_SCHAR(int) NCX_PUTN_SCHAR(long) NCX_PUTN_SCHAR(float) NCX_PUTN_SCHAR(double) dnl NCX_PAD_PUTN_SCHAR(schar) int ncx_pad_putn_schar_schar(void **xpp, size_t nelems, const schar *tp) { NCX_PAD_PUTN_Byte_Body } dnl NCX_PAD_PUTN_SCHAR(uchar) int ncx_pad_putn_schar_uchar(void **xpp, size_t nelems, const uchar *tp) { NCX_PAD_PUTN_Byte_Body } NCX_PAD_PUTN_SCHAR(short) NCX_PAD_PUTN_SCHAR(int) NCX_PAD_PUTN_SCHAR(long) NCX_PAD_PUTN_SCHAR(float) NCX_PAD_PUTN_SCHAR(double) /* short */ NCX_GETN(short, schar) NCX_GETN(short, uchar) #if X_SIZEOF_SHORT == SIZEOF_SHORT /* optimized version */ int ncx_getn_short_short(const void **xpp, size_t nelems, short *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(short)); # else swapn2b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_SHORT); return ENOERR; } #else NCX_GETN(short, short) #endif NCX_GETN(short, int) NCX_GETN(short, long) NCX_GETN(short, float) NCX_GETN(short, double) NCX_PAD_GETN_SHORT(schar) NCX_PAD_GETN_SHORT(uchar) NCX_PAD_GETN_SHORT(short) NCX_PAD_GETN_SHORT(int) NCX_PAD_GETN_SHORT(long) NCX_PAD_GETN_SHORT(float) NCX_PAD_GETN_SHORT(double) NCX_PUTN(short, schar) NCX_PUTN(short, uchar) #if X_SIZEOF_SHORT == SIZEOF_SHORT /* optimized version */ int ncx_putn_short_short(void **xpp, size_t nelems, const short *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_SHORT); # else swapn2b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_SHORT); return ENOERR; } #else NCX_PUTN(short, short) #endif NCX_PUTN(short, int) NCX_PUTN(short, long) NCX_PUTN(short, float) NCX_PUTN(short, double) NCX_PAD_PUTN_SHORT(schar) NCX_PAD_PUTN_SHORT(uchar) NCX_PAD_PUTN_SHORT(short) NCX_PAD_PUTN_SHORT(int) NCX_PAD_PUTN_SHORT(long) NCX_PAD_PUTN_SHORT(float) NCX_PAD_PUTN_SHORT(double) /* int */ NCX_GETN(int, schar) NCX_GETN(int, uchar) NCX_GETN(int, short) #if X_SIZEOF_INT == SIZEOF_INT /* optimized version */ int ncx_getn_int_int(const void **xpp, size_t nelems, int *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(int)); # else swapn4b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else NCX_GETN(int, int) #endif #if X_SIZEOF_INT == SIZEOF_LONG /* optimized version */ int ncx_getn_int_long(const void **xpp, size_t nelems, long *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(long)); # else swapn4b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else NCX_GETN(int, long) #endif NCX_GETN(int, float) NCX_GETN(int, double) NCX_PUTN(int, schar) NCX_PUTN(int, uchar) NCX_PUTN(int, short) #if X_SIZEOF_INT == SIZEOF_INT /* optimized version */ int ncx_putn_int_int(void **xpp, size_t nelems, const int *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_INT); # else swapn4b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else NCX_PUTN(int, int) #endif #if X_SIZEOF_INT == SIZEOF_LONG /* optimized version */ int ncx_putn_int_long(void **xpp, size_t nelems, const long *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_INT); # else swapn4b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else NCX_PUTN(int, long) #endif NCX_PUTN(int, float) NCX_PUTN(int, double) /* float */ NCX_GETN(float, schar) NCX_GETN(float, uchar) NCX_GETN(float, short) NCX_GETN(float, int) NCX_GETN(float, long) #if X_SIZEOF_FLOAT == SIZEOF_FLOAT && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_getn_float_float(const void **xpp, size_t nelems, float *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(float)); # else swapn4b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_FLOAT); return ENOERR; } #elif vax int ncx_getn_float_float(const void **xpp, size_t nfloats, float *ip) { float *const end = ip + nfloats; while(ip < end) { GET_VAX_DFLOAT_Body(`(*xpp)') ip++; *xpp = (char *)(*xpp) + X_SIZEOF_FLOAT; } return ENOERR; } #elif _SX && _FLOAT2 int ncx_getn_float_float(const void **xpp, size_t nelems, float *tp) { const char *const xp = *xpp; const int ncnv = ie3_fl2(xp, tp, 4, 8, nelems); *xpp = xp + nelems * X_SIZEOF_FLOAT; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_getn_float_float(const void **xpp, size_t nelems, float *tp) { const char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #endif NCX_GETN(float, double) NCX_PUTN(float, schar) NCX_PUTN(float, uchar) NCX_PUTN(float, short) NCX_PUTN(float, int) NCX_PUTN(float, long) #if X_SIZEOF_FLOAT == SIZEOF_FLOAT && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_putn_float_float(void **xpp, size_t nelems, const float *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_FLOAT); # else swapn4b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_FLOAT); return ENOERR; } #elif vax int ncx_putn_float_float(void **xpp, size_t nfloats, const float *ip) { const float *const end = ip + nfloats; while(ip < end) { PUT_VAX_DFLOAT_Body(`(*xpp)') ip++; *xpp = (char *)(*xpp) + X_SIZEOF_FLOAT; } return ENOERR; } #elif _SX && _FLOAT2 int ncx_putn_float_float(void **xpp, size_t nelems, const float *tp) { char *const xp = *xpp; const int ncnv = fl2_ie3(tp, xp, 8, 4, nelems); *xpp = xp + nelems * X_SIZEOF_FLOAT; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_putn_float_float(void **xpp, size_t nelems, const float *tp) { char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #endif NCX_PUTN(float, double) /* double */ NCX_GETN(double, schar) NCX_GETN(double, uchar) NCX_GETN(double, short) NCX_GETN(double, int) NCX_GETN(double, long) NCX_GETN(double, float) dnl NCX_GETN(double, double) #if X_SIZEOF_DOUBLE == SIZEOF_DOUBLE && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_getn_double_double(const void **xpp, size_t nelems, double *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(double)); # else swapn8b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_DOUBLE); return ENOERR; } #elif vax int ncx_getn_double_double(const void **xpp, size_t ndoubles, double *ip) { double *const end = ip + ndoubles; while(ip < end) { GET_VAX_DDOUBLE_Body(`(*xpp)') ip++; *xpp = (char *)(*xpp) + X_SIZEOF_DOUBLE; } return ENOERR; } /* vax */ #elif _SX && _FLOAT2 int ncx_getn_double_double(const void **xpp, size_t nelems, double *tp) { const char *const xp = *xpp; const int ncnv = ie3_fl2(xp, tp, 8, 8, nelems); *xpp = xp + nelems * X_SIZEOF_DOUBLE; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_getn_double_double(const void **xpp, size_t nelems, double *tp) { const char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #endif NCX_PUTN(double, schar) NCX_PUTN(double, uchar) NCX_PUTN(double, short) NCX_PUTN(double, int) NCX_PUTN(double, long) NCX_PUTN(double, float) dnl NCX_PUTN(double, double) #if X_SIZEOF_DOUBLE == SIZEOF_DOUBLE && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_putn_double_double(void **xpp, size_t nelems, const double *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_DOUBLE); # else swapn8b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_DOUBLE); return ENOERR; } #elif vax int ncx_putn_double_double(void **xpp, size_t ndoubles, const double *ip) { const double *const end = ip + ndoubles; while(ip < end) { PUT_VAX_DDOUBLE_Body(`(*xpp)') ip++; *xpp = (char *)(*xpp) + X_SIZEOF_DOUBLE; } return ENOERR; } /* vax */ #elif _SX && _FLOAT2 int ncx_putn_double_double(void **xpp, size_t nelems, const double *tp) { char *const xp = *xpp; const int ncnv = fl2_ie3(tp, xp, 8, 8, nelems); *xpp = xp + nelems * X_SIZEOF_DOUBLE; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_putn_double_double(void **xpp, size_t nelems, const double *tp) { char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #endif /* * Other aggregate conversion functions. */ /* text */ int ncx_getn_text(const void **xpp, size_t nelems, char *tp) { NCX_GETN_Byte_Body } int ncx_pad_getn_text(const void **xpp, size_t nelems, char *tp) { NCX_PAD_GETN_Byte_Body } int ncx_putn_text(void **xpp, size_t nelems, const char *tp) { NCX_PUTN_Byte_Body } int ncx_pad_putn_text(void **xpp, size_t nelems, const char *tp) { NCX_PAD_PUTN_Byte_Body } /* opaque */ int ncx_getn_void(const void **xpp, size_t nelems, void *tp) { NCX_GETN_Byte_Body } int ncx_pad_getn_void(const void **xpp, size_t nelems, void *tp) { NCX_PAD_GETN_Byte_Body } int ncx_putn_void(void **xpp, size_t nelems, const void *tp) { NCX_PUTN_Byte_Body } int ncx_pad_putn_void(void **xpp, size_t nelems, const void *tp) { NCX_PAD_PUTN_Byte_Body } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/README.netcdf0000644000175000017500000000636511606020250022614 0ustar amckinstryamckinstry Unidata NetCDF The Unidata network Common Data Form (netCDF) is an interface for scientific data access and a freely-distributed software library that provides an implementation of the interface. The netCDF library also defines a machine-independent format for representing scientific data. Together, the interface, library, and format support the creation, access, and sharing of scientific data. The current netCDF software provides C, Fortran-77, Fortran-90, and C++ interfaces for applications and data. It has been tested on various common platforms. NetCDF files are self-describing, network-transparent, directly accessible, and extendible. `Self-describing' means that a netCDF file includes information about the data it contains. `Network-transparent' means that a netCDF file is represented in a form that can be accessed by computers with different ways of storing integers, characters, and floating-point numbers. `Direct-access' means that a small subset of a large dataset may be accessed efficiently, without first reading through all the preceding data. `Extendible' means that data can be appended to a netCDF dataset without copying it or redefining its structure. NetCDF is useful for supporting access to diverse kinds of scientific data in heterogeneous networking environments and for writing application software that does not depend on application-specific formats. A variety of analysis and display packages have been developed to analyze and display data in netCDF form. For more information about netCDF, see the netCDF Web page at http://www.unidata.ucar.edu/software/netcdf/ You can obtain a copy of the latest released version of netCDF software using a WWW browser or anonymous FTP from ftp://ftp.unidata.ucar.edu/pub/netcdf/netcdf.tar.Z Included in this distribution are: the C source for the netCDF data access library, sources for the FORTRAN and C++ interfaces, documentation for the netCDF library and utilities in the form of a netCDF User's Guide, source for the netCDF utilities ncdump and ncgen, and test programs to verify the correct implementation of the netCDF library. Legal stuff (copyright, licensing restrictions, etc.) can be found in the file COPYRIGHT. To install this package, please see the file INSTALL in the distribution, or the (possibly more up-to-date) document: http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-install/ The netCDF-3 C and FORTRAN-77 interfaces are documented in man(1) pages in the distribution in files netcdf.3 and netcdf.3f, respectively, or at http://www.unidata.ucar.edu/software/netcdf/docs User's Guides for C, FORTRAN, and FORTRAN-90 are also available in several forms from the same location. A mailing list, netcdfgroup@unidata.ucar.edu, exists for discussion of the netCDF interface and announcements about netCDF bugs, fixes, and enhancements. For information about how to subscribe, see the URL http://www.unidata.ucar.edu/software/netcdf/mailing-lists.html An archive of past postings to the netcdfgroup mailing list is available for searching from the netCDF home page. We appreciate feedback from users of this package. Please send comments, suggestions, and bug reports to . Please identify the version of the package (file VERSION). xdmf-2.1.dfsg.1/Utilities/vtknetcdf/error.c0000644000175000017500000001041211606020250021753 0ustar amckinstryamckinstry/* * Copyright 1993, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: error.c,v 1.14 90/02/23 16:08:55 davis Exp */ /*LINTLIBRARY*/ #include "ncconfig.h" #include #include #include /* If netcdf-4 is in use, rename all nc_ functions to nc3_ functions. */ #ifdef USE_NETCDF4 #include #include #else #include "netcdf.h" #endif #ifndef NO_STRERROR #include /* contains prototype for ansi libc function strerror() */ #else /* provide a strerror function for older unix systems */ static char * strerror(int errnum) { extern int sys_nerr; extern char *sys_errlist[]; if(errnum < 0 || errnum >= sys_nerr) return NULL; /* else */ return sys_errlist[errnum]; } #endif /* NO_STRERROR */ #ifdef vms /* UNTESTED */ /* * On the vms system, when a system error occurs which is not * mapped into the unix styled errno values, errno is set EVMSERR * and a VMS error code is set in vaxc$errno. * This routine prints the systems message associated with status return * from a system services call. */ #include #include #include static const char * vms_strerror( int status ) { short msglen; static char msgbuf[256]; $DESCRIPTOR(message, msgbuf); register ret; msgbuf[0] = 0; ret = SYS$GETMSG(status, &msglen, &message, 15, 0); if(ret != SS$_BUFFEROVF && ret != SS$_NORMAL) { (void) strcpy(msgbuf, "EVMSERR"); } return(msgbuf); } #endif /* vms */ static char unknown[] = "Unknown Error"; const char * nc_strerror(int err) { #ifdef vms if(err == EVMSERR) { return vms_strerror(err); } /* else */ #endif /* vms */ if(NC_ISSYSERR(err)) { const char *cp = (const char *) strerror(err); if(cp == NULL) return unknown; /* else */ return cp; } /* else */ switch (err) { case NC_NOERR: return "No error"; case NC_EBADID: return "NetCDF: Not a valid ID"; case NC_ENFILE: return "NetCDF: Too many files open"; case NC_EEXIST: return "NetCDF: File exists && NC_NOCLOBBER"; case NC_EINVAL: return "NetCDF: Invalid argument"; case NC_EPERM: return "NetCDF: Write to read only"; case NC_ENOTINDEFINE: return "NetCDF: Operation not allowed in data mode"; case NC_EINDEFINE: return "NetCDF: Operation not allowed in define mode"; case NC_EINVALCOORDS: return "NetCDF: Index exceeds dimension bound"; case NC_EMAXDIMS: return "NetCDF: NC_MAX_DIMS exceeded"; case NC_ENAMEINUSE: return "NetCDF: String match to name in use"; case NC_ENOTATT: return "NetCDF: Attribute not found"; case NC_EMAXATTS: return "NetCDF: NC_MAX_ATTRS exceeded"; case NC_EBADTYPE: return "NetCDF: Not a valid data type or _FillValue type mismatch"; case NC_EBADDIM: return "NetCDF: Invalid dimension ID or name"; case NC_EUNLIMPOS: return "NetCDF: NC_UNLIMITED in the wrong index"; case NC_EMAXVARS: return "NetCDF: NC_MAX_VARS exceeded"; case NC_ENOTVAR: return "NetCDF: Variable not found"; case NC_EGLOBAL: return "NetCDF: Action prohibited on NC_GLOBAL varid"; case NC_ENOTNC: return "NetCDF: Unknown file format"; case NC_ESTS: return "NetCDF: In Fortran, string too short"; case NC_EMAXNAME: return "NetCDF: NC_MAX_NAME exceeded"; case NC_EUNLIMIT: return "NetCDF: NC_UNLIMITED size already in use"; case NC_ENORECVARS: return "NetCDF: nc_rec op when there are no record vars"; case NC_ECHAR: return "NetCDF: Attempt to convert between text & numbers"; case NC_EEDGE: return "NetCDF: Start+count exceeds dimension bound"; case NC_ESTRIDE: return "NetCDF: Illegal stride"; case NC_EBADNAME: return "NetCDF: Name contains illegal characters"; case NC_ERANGE: return "NetCDF: Numeric conversion not representable"; case NC_ENOMEM: return "NetCDF: Memory allocation (malloc) failure"; case NC_EVARSIZE: return "NetCDF: One or more variable sizes violate format constraints"; case NC_EDIMSIZE: return "NetCDF: Invalid dimension size"; case NC_ETRUNC: return "NetCDF: File likely truncated or possibly corrupted"; } /* default */ return unknown; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/RELEASE_NOTES0000644000175000017500000007351611606020250022447 0ustar amckinstryamckinstryThis file contains a high-level description of this package's evolution. Entries are in reverse chronological order (most recent first). VERSION COMMENTS ------- -------- 3.6.2 beta6 2007-01-20 Fine tuning of build system to properly handle cygwin, Mingw, and strange configuration issues. Automake 1.10 has a problem with running our tests on MinGW, so I'm switching back to automake 1.9.6 for this release. 3.6.2 beta5 2006-12-30 Now netCDF configuration uses autoconf 2.61, and automake 1.10. (Thanks to Ralf Wildenhues for the patches, and all the autotools help in general!) Final major revision (I hope!) of netCDF tutorial before the 3.6.2 release. Now the tutorial contains all the content that I think it should. (Ed) Now netCDF builds under MinGW, producing a windows DLL with the C and F77 APIs. Use the --enable-shared --enable-dll --disable-cxx --disable-f90 flags to configure. (C++ and F90 have never been built as windows DLLs, but might be in a future release if there is user interest). This has all been documented in the netCDF Porting and Installation Guide. Now extreme numbers (i.e. those close to the limits of their type) can be turned off in nc_test/nf_test, with --disable-extreme-numbers. It is turned off automatically for Solaris i386 systems. Added --enable-c-only option to configure. This causes only the core netCDF-3 C library to be built. It's the same as --disable-f77 --disable-cxx --disable-v2 --disable-utilities. Added --disable-utilities to turn off building and testing of ncgen/ncdump. Fix a long-standing bug in nf90_get_att_text() pointed out by Ryo Furue, to make sure resulting string is blank-padded on return. This is fixed in the Fortran-90 interface, but is impractical to fix in the Fortran-77 interface implemented via cfortran.h. Now large file tests are run if --enable-large-file-tests is used in the configure. For Cray users, the ffio module is used if the --enable-ffio option is passed to configure. Unrolled loops in byte-swapping code used on little-endian platforms to reduce loop overhead. This optimization resulted in a 22% speedup for some applications accessing floats or ints (e.g. NCO utilities ncap and ncbo) and a smaller speedup for shorts or doubles. Added "-k" option to ncdump and ncgen, for identifying and specifying the kind of netCDF file, one of "classic", "64-bit-offset", "hdf5", or "hdf5-nc3". Removed output of kind of netCDF file in CDL comment produced by ncdump. Fixed bug of ncdump seg-faulting if invoked incorrectly with option like "-c" or "-h" but no file name. 3.6.2 beta4 2006-08-15 Changed F77/F90 man pages from netcdf.3f and netcdf.3f90 to netcdf_f77.3 and netcdf_f90.3. Also fixed broken install of man pages. Changed configure script so that "-g -O2" is no longer set as CFLAGS, CXXFLAGS, and FFLAGS by default if a GNU compiler is being used. Now nothing is set. Changed configure script so that fortran flag is set in config.h. Updated Installation and Porting Guide, C++ Interface Guide, F77 and F90 Interface Guides. Build with static libraries by default. Added configure option --enable-separate-fortran, which causes the fortran library to be built separately. This is turned on automatically for shared libraries. Improved clarity of error messages. Changed configuration to get cygwin DLL and mingw DLL builds working, for the C library only (i.e. no F77, F90, or C++ APIs). Changed type of ncbyte in C++ interface from unsigned char to signed char, for consistency with C interface. The C++ documentation warned this change would eventually occur. Changed the C++ interface to use only the netCDF-3 C interface instead of the older netCDF-2 C interface. This has the added benefit that on-the-fly numeric conversions are now supported using get methods, for example you can get data of any type as double. When using --disable-v2 flag to configure, the C++ interface can now be built and installed. 3.6.2 beta3 2006-05-24 Changed to use default prefix of /usr/local instead of package-based prefix of previous releases of netCDF. Use the --prefix argument to the configure script to override the default. Made separate fortran library file, instead of appending fortran library functions to the C library file, if --enable-separate-fortran is used during configure (it's turned on automatically if --enable-shared is used). If uses, the fortran API users must link to *both* the C library and the new fortran library, like this: -lnetcdff -lnetcdf Added netCDF examples in C, C++, F77, F90, and CDL. See the examples subdirectory. Added the NetCDF Tutorial. Minor fixes to some of the netCDF documentation. Made it possible to build without V2 API using --disable-v2 from configure. Switched to new build system, with automake and libtool. Now shared libraries are built (as well as static ones) on platforms which support it. For more information about shared libraries, see http://www.unidata.ucar.edu/software/netcdf/docs/faq.html#shared_intro Fixed ncdump crash that happened when no arguments were used. Fixed for building with gfortran 4.1.0. Important fix for machines whose SIZEOF_SIZE_T != SIZEOF_LONG, such as NEC-SX, thanks to Stephen Leak. Fixed C++ on AIX platform. Fixed 64-bit builds on AIX platform. Removed bad assertion that could be triggered in rare cases when reading a small file. Added comments in v1hpg.c to clarify purpose of each internal function. Make sure filesize is determined in nc_close() *after* buffers get flushed. Fix long-standing problem resulting in files up to 3 bytes longer than necessary if there is exactly one record variable of type byte, char, or short and if the number of values per record for that variable is not divisible by 4 (or 2 in the case of short). Now the filesize determined from header info by NC_calcsize should be correct in all cases. 3.6.1 2006-01-31 Updated installation manual for 3.6.1. Changed installation to try to provide correct compiler flags for compiling in 64-bit mode on Sun, Irix, AIX, and HPUX. (HPUX doesn't work for me, however). Now run configure with --enable-64bit to get a 64 bit compile. Fixed long-standing bug that would cause small netCDF files to be padded on the end with zero bytes to 4096 bytes when they were opened and changed. Now small files should stay small after you change a value. Fixed bug in assertions in putget.c that would only be noticed if you change the manifest constant NC_MAX_DIMS in netcdf.h to be different from NC_MAX_VAR_DIMS. Moved test ftest.F from fortran to nf_test directory, and fixed bug in ftest.F which caused it to return 0 even if tests failed (no tests were failing, however). Also renamed some test output files to make things a little clearer. If open for writing, pad with up to 3 extra zero bytes before close to the correct canonical length, calculated from the header. Previously files could be short due to not padding when writing in NOFILL mode. Doubled arbitrary limits on number of dimensions, variables, attributes, and length of names. Change name of nc_get_format() to nc_inq_format(). Add analogous interfaces for nf_inq_format(), nf90_inquire(), and NcFile::get_format() to f77, f90, and C++ interfaces. Document new function in texinfo files. Add minimal test to nc_test, nf_test. 3.6.1-beta3 2005-02-17 Added function nc_get_format(int ncid, int* formatp) that returns either NC_FORMAT_CLASSIC or NC_FORMAT_64BIT for a CDF1 or CDF2 file, respectively. Added test to nc_test that detects whether format version was changed after a file is reopened and define mode is entered. Correctly configure for Intel ifort Fortran compiler on Linux. 3.6.0-p1 2005-02-18 Fixed bug that changes CDF2 files to CDF1 files if CDF2 file is reopened for write access and either an attribute is changed or define mode is entered. 3.6.1-beta2 2005-1-6 Fixed absoft compile problem. Maybe. 3.6.1-beta1 2005-1-3 Fixed Cygwin C++ problem. Fixed large file problem in MS Visual C++.NET environment. More information in installation and porting guide. 3.6.0 2004-12-16 Added texinfo source for the documentation. Added large file tests to Windows directory in distribution. Modified win32 visual studio project files so that m4 is no longer required to build netcdf under visual studio. Modified rules.make to use install instead of cp, fixing install problem for cygwin users. Modified configure/install stuff to support HP-UX. Modified configure/install stuff to support G95. In the f90 interface, applied Arnaud Desitter's fixes to correct mismatches between scalar and array arguments, eliminating (legitimate) complaints by the NAGWare f95 compiler. Also fixed bugs introduced in 3.6.0-beta5 in the mapped array interfaces. 3.6.0-beta6 2004-10-05 Fixed AIX 64-bit/largefile install problems. Removed FAQ section from netcdf.texi User's Guide, in deference to online version that can be kept up to date more easily. 3.6.0-beta5 2004-10-04 Fixed assertion violation on 64-bit platforms when size of last fixed size variable exceeds 2^32 - 1. Removed another restriction on file size by making record size (derived from other sizes, not part of the format) an off_t instead of a size_t, when an off_t is larger than a size_t. This permits records to be *much* larger in either classic format or 64-bit-offset format. Incorporated patch from Mathis Rosenhauer to improve performance of Fortran 90 interface for calls to nf90_put_var_TYPE(), nf90_get_var_TYPE(), nf90_put_vara_TYPE(), and nf90_get_vara_TYPE() functions by not emulating them with the corresponding nf90_put_varm_TYPE() and nf90_get_varm_TYPE() calls. Added tests for invalid offsets in classic format when defining multiple large variables. Improved installation ease. Have configure script use Large File Support as a default, if available. Add "extra_test" as a target for testing Large File Support. 3.6.0-beta3 2004-08-24 Upgraded to recent autoconf, changed configure to (hopefully) improve installation. Also added macros to deal with large file systems. Added nf_set_default_format to Fortran interface. Added testing to the set_default_format functions to nc_test and nf_test. Added documentation to the man page for set_default_format functions. Added two new error return codes to C, f77, and f90 interfaces for invalid dimension size and for bad variable size. Made test for max dimension size depend on whether 64-bit offsets used. Fixed bug with dimension sizes between 2^31 and 2^32 (for byte variables). Fixed ncdump to properly print dimensions larger than 2^31. Fixed ncgen to properly handle dimensions between 2^31 and 2^32. 3.6.0-beta2 Added -v2 (version 2 format with 64-bit offsets) option to ncgen, to specify that generated files or generated C/Fortran code should create 64-bit offset files. Also added -x option to ncgen to specify use of no-fill mode for fast creation of large files. Added function to set default create mode to C interface (nc_set_default_create). Added win32 directory, with NET subdirectory to hold .NET port of netCDF. To use, open netcdf.sln with Visual Studio, and do a clean and then a build of either the debug or release builds. Tests will be run as part of the build process. VC++ with managed extensions is required (i.e. VC++.NET). Added windows installer files to build windows binary installs. 3.6.0-beta1 By incorporating Greg Sjaardema's patch, added support for 64-bit offset files, which remove many of the restrictions relating to very large files (i.e. larger than 2 GB.) This introduces a new data format for the first time since the original netCDF format was introduced. Files in this new 64-bit offset format can't be read by earlier versions of netCDF. Users should continue to use the netCDF classic format unless they need to create very large files. The test suite, nc_test, will now be run twice, once for netCDF classic format testing, and once for 64-bit offset format testing. The implementation of the Fortran-77 interface has been adapted to version 4.3 of Burkhard Burow's "cfortran.h". 3.6.0-alpha Added NEC SX specific optimization for NFILL tunable parameter in libsrc/putget.c Added support for the ifc Fortran-90 compiler creating files "netcdf.d" and "typesizes.d" (instead of ".mod" files). Fixed access to iargc and getarg functions from Fortran-90 for NAG f90 compiler, contributed by Harald Anlauf. 3.5.1 2004-02-03 Updated INSTALL.html for Mac OS X (Darwin). Made the installation of the netCDF Fortran-90 module file more robust regarding the name of the file. Added support for eight-byte integers in Fortran90 interface. Increased advisory limits in C netcdf.h and Fortran netcdf.inc for maximum number of dimensions, variables, and attributes. Changed C++ declarations "friend NcFile" to "friend class NcFile" in cxx/netcdfcpp.h to conform to standard. Added Dan Schmitt's backward compatible extension to the C++ record interface to work with arbitrary dimension slices. Added C++ documentation note that caller is responsible for deleting pointer returned by Variable::values() method when no longer needed. Made C++ interface more standard; the result may not compile on some old pre-standard C++ compilers. Fixed bug in ncgen when parsing values of a multidimensional char variable that resulted in failure to pad a value with nulls on IRIX. Fixed ncdump bug adding extra quote to char variable data when using -fc or -ff option. Fixed so compiling with -DNO_NETCDF_2 will work for building without backward-compatibility netCDF-2 interfaces. Eliminated use of ftruncate(), because it fails on FAT32 file systems under Linux. Initialized a pointer in putget.m4 (used to generate putget.c) that was involved in uninitialized memory references when nc_test is run under Purify. Two users had reported seeing crashes resulting from this problem in their applications. Reverted pointer initializations in putget.m4, after testing revealed these caused a performance problem, resulting in many extra calls to px_pgin and px_pgout when running nc_test. Added checking of size of "dimids" vector in function nf90_inquire_variable(...) and error-returning if it isn't sufficiently capacious. Added variable index to ncvarget() and ncattinq() error messages and attribute name to ncattinq() error message. Tweaked configure script to work with recent C++ compilers. Fixed a memory leak in C++ interface, making sure NcVar::cur_rec[] gets deleted in NcVar destructor. Reimplemented nc_sync() fix of version 3.5.0 to eliminate performance penalty when synchronization is unnecessary. Changed order of targets in Makefile to build Fortran interface last, as a workaround for problem with make on AIX platforms. 3.5.0 2001-03-23 Added Fortran 90 interface. Changed C macro TIMELEN in file cxx/nctst.cpp to TIMESTRINGLEN to avoid clash with macro defined on AIX systems in /usr/include/time.h. Fixed miswriting of netCDF header when exiting define mode. Because the header was always written correctly later, this was only a problem if there was another reader of the netCDF file. Fixed explicit synchronizing between netCDF writer and readers via the nc_sync(), nf_sync(), and ncsync() functions. Fixed a number of bugs related to attempts to support shrinking the header in netCDF files when attributes are rewritten or deleted. Also fixed the problem that nc__endef() did not work as intended in reserving extra space in the file header, since the extra space would be compacted again on calling nc_close(). Fixed the "redef bug" that occurred when nc_enddef() or nf_enddef() is called after nc_redef() or nf_redef(), the file is growing such that the new beginning of a record variable is in the next "chunk", and the size of at least one record variable exceeds the chunk size (see netcdf.3 man page for a description of this tuning parameter and how to set it). This bug resulted in corruption of some values in other variables than the one being added. The "__" tuning functions for the Fortran interface, nf__create, nf__open, and nf__enddef, are now documented in the Fortran interface man pages. Add an 'uninstall' target to all the Makefiles. Dave Glowacki 199810011851.MAA27335 Added support for multiprocessing on Cray T3E. Hooks added by Glenn, but the majority of the work was done at NERSC. Also includes changes to ffio option specification. Patch rollup provided by R. K. Owen . The following functions are added to the public interface. nc__create_mp() nc__open_mp() nc_set_base_pe() nc_inq_base_pe() Fixed makefile URL for Win32 systems in INSTALL file. Made test for UNICOS system in the configure script case independent. Ported to the following systems: AIX 4.3 (both /bin/xlc and /usr/vac/bin/xlc compilers) IRIX 6.5 IRIX64 6.5 Changed the extension of C++ files from ".cc" to ".cpp". Renamed the C++ interface header file "netcdfcpp.h" instead of "netcdf.hh", changing "netcdf.hh" to include "netcdfcpp.h" for backward compatibility. Treat "FreeBSD" systems the same as "BSD/OS" system w.r.t. Fortran and "whatis" database. Corrected manual pages: corrected spelling of "enddef" (was "endef") and ensured that the words "index" and "format" will be correctly printed. Updated support for Fortran-calling-C interface by updating "fortran/cfortran.h" from version 3.9 to version 4.1. This new version supports the Portland Group Fortran compiler (C macro "pgiFortran") and the Absoft Pro Fortran compiler (C macro "AbsoftProFortran"). Corrected use of non-integral-constant-expression in specifying size of temporary arrays in file "libsrc/ncx_cray.c". Added Compaq Alpha Linux workstation example to INSTALL file. Ported cfortran.h to Cygnus GNU Win32 C compiler (gcc for Windows). Fixed bug in ncdump using same CDL header name when called with multiple files. Added new NULL data type NC_NAT (Not A Type) to facilitate checking whether a variable object has had its type defined yet, for example when working with packed values. Fixed use of compile-time macro NO_NETCDF_2 so it really doesn't include old netCDF-2 interfaces, as intended. Ported to MacOS X Public Beta (Darwin 1.2/PowerPC). Fixed C++ friend declarations to conform to C++ standard. Changed INSTALL file to INSTALL.html instead. 3.4 1998-03-09 Fixed ncx_cray.c to work on all CRAY systems, not just CRAY1. Reworked USE_IEG, which was incorrect. Reworked short support. Now USE_IEG and otherwise both pass t_ncx. To better support parallel systems, static and malloc'ed scratch areas which were shared in the library were eliminated. These were made private and on the stack where possible. To support this, the macros ALLOC_ONSTACK and FREE_ONSTACK are defined in onstack.h. The buffered i/o system implementation in posixio.c was reimplemented to limit the number and size of read() or write() system calls and use greater reliance on memory to memory copy. This saves a great deal of wall clock time on slow (NFS) filesystems, especially during nc_endef(). Added performance tuning "underbar underbar" interfaces nc__open(), nc__create(), and nc__enddef(). The 'sizehint' contract between the higher layers and the ncio layer is consistently enforced. The C++ interface has been updated so that the deprecated "nclong" typedef should no longer be required, and casts to nclong no longer necessary. Just use int or long as appropriate. nclong is still supported for backwards compatibility. The ncdump utility now displays byte values as signed, even on platforms where the type corresponding to a C char is unsigned (SGI, for example). Also the ncdump and ncgen utilities have been updated to display and accept byte attributes as signed numeric values (with a "b" suffix) instead of using character constants. In libsrc/error.c:nc_strerror(int), explain that NC_EBADTYPE applies to "_FillValue type mismatch". Some changes to configure scripts (aclocal.m4), macros.make.in and ncgen/Makefile to support NEC SUPER-UX 7.2. The "usage" messages of ncgen and ncdump include the string returned from nc_inq_libvers(). Corrected some casts in the library so that all phases of the arithmetic computing file offsets occurs with "off_t" type. This allows certain larger netcdf files to be created and read on systems with larger (64bit) off_t. In ncgen, multidimensional character variables are now padded to the length of last dimension, instead of just concatenating them. This restores an undocumented but convenient feature of ncgen under netCDF-2. Also, a syntax error is now reliably reported if the netcdf name is omitted in CDL input. Fortran and C code generated by ncgen for netCDF components whose names contain "-" characters will now compile and run correctly instead of causing syntax errors. The library allows "." characters in names as well as "_" and "-" characters. A zero length name "" is explicitly not allowed. The ncgen utility will now permit "." characters in CDL names as well. Memory leaks in the C++ interface NcVar::as_*() member functions and NcFile::add_var() member function are fixed. The documentation was fixed where it indicated incorrectly that the library managed value blocks that the user is actually responsible for deleting. The values of the version 2 Fortran error codes have been modified to make the version 2 Fortran interface more backward compatible at the source level. Added support for systems whose Fortran INTEGER*1 and INTEGER*2 types are equivalent to the C "long" type but whose C "int" and "long" types differ. An example of such a system is the NEC SX-4 with the "-ew" option to the f90 compiler (sheesh, what a system!). Fixed Version 2 Fortran compatibility bug: NCVGTG, NCVGGC, NCVPTG, and NCVPGC didn't work according to the Version 2 documentation if the innermost mapping value (i.e. IMAP[1]) was zero (indicating that the netCDF structure of the variable should be used). 3.3.1 1997-06-16 One can now inquire about the number of attributes that a variable has using the global variable ID. The FORTRAN interface should now work on more systems. In particular: It should now work with FORTRAN compilers whose "integer*1" datatype is either a C "signed char", "short", or "int" and whose "integer*2" datatype is either a C "short" or "int". It should now work with FORTRAN compilers that are extremely picky about source code formatting (e.g. the NAG f90 compiler). The dependency on the non-POSIX utility m4(1) for generating the C and FORTRAN manual pages has been eliminated. EXTERNAL statements have been added to the FORTRAN include-file "netcdf.inc" to eliminate excessive warnings about "unused" variables (which were actually functions) by some compilers (e.g. SunOS 4.1.3's f77(1) version 1.x). Building the netCDF-3 package no longer requires the existence of the Standard C macro RAND_MAX. Fixed an ncdump bug resulting in ncdump reporting Attempt to convert between text & numbers when _FillValue attribute of a character variable set to the empty string "". Made ncgen tests more stringent and fixed various bugs this uncovered. These included bugs in handling byte attributes on platforms on which char is unsigned, initializing scalar character variables in generated C code under "-c" option, interspersing DATA statements with declaration statements in generated Fortran code under "-f" option, handling empty string as a value correctly in generated C and Fortran, and handling escape characters in strings. The Fortran output under the "-f" option was also made less obscure and more portable, using automatic conversion with netCDF-3 interfaces instead of "BYTE", "INTEGER*1", or "INTEGER*2" declarations. Fixed a C++ interface problem that prevented compiling the C++ library with Digital's cxx compiler. Made ncgen "make test" report failure and stop if test resulted in a failure of generated C or Fortran code. The file that you are now reading was created to contain a high-level description of the evolution of the netCDF-3 package. 3.3 1997-05-15 The production version of the netCDF-3 package was released. A comparison of the netCDF-2 and netCDF-3 releases can be found in the file COMPATIBILITY. xdmf-2.1.dfsg.1/Utilities/vtknetcdf/string.c0000644000175000017500000000466611606020250022146 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: string.c,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #include "nc.h" #include #include #include #include #include "ncx.h" #include "rnd.h" /* * Free string, and, if needed, its values. * Formerly NC_free_string() */ void free_NC_string(NC_string *ncstrp) { if(ncstrp==NULL) return; free(ncstrp); } /* * Verify that a name string is valid * CDL syntax, eg, all the characters are * alphanumeric, '-', '_', '+', or '.'. * Also permit ':', '@', '(', or ')' in names for chemists currently making * use of these characters, but don't document until ncgen and ncdump can * also handle these characters in names. */ int NC_check_name(const char *name) { const char *cp = name; assert(name != NULL); if(*name == 0) return NC_EBADNAME; /* empty names disallowed */ for(; *cp != 0; cp++) { int ch = *cp; if(!isalnum(ch)) { if(ch != '_' && ch != '-' && ch != '+' && ch != '.' && ch != ':' && ch != '@' && ch != '(' && ch != ')') return NC_EBADNAME; } } if(cp - name > NC_MAX_NAME) return NC_EMAXNAME; return NC_NOERR; } /* * Allocate a NC_string structure large enough * to hold slen characters. * Formerly NC_new_string(count, str) */ NC_string * new_NC_string(size_t slen, const char *str) { NC_string *ncstrp; size_t sz = M_RNDUP(sizeof(NC_string)) + slen + 1; #if 0 sz = _RNDUP(sz, X_ALIGN); #endif ncstrp = (NC_string *)malloc(sz); if( ncstrp == NULL ) return NULL; (void) memset(ncstrp, 0, sz); ncstrp->nchars = sz - M_RNDUP(sizeof(NC_string)) - 1; assert(ncstrp->nchars + 1 > slen); ncstrp->cp = (char *)ncstrp + M_RNDUP(sizeof(NC_string)); if(str != NULL && *str != 0) { (void) strncpy(ncstrp->cp, str, ncstrp->nchars +1); ncstrp->cp[ncstrp->nchars] = 0; } return(ncstrp); } /* * If possible, change the value of an NC_string to 'str'. * * Formerly NC_re_string() */ int set_NC_string(NC_string *ncstrp, const char *str) { size_t slen; size_t diff; assert(str != NULL && *str != 0); slen = strlen(str); if(ncstrp->nchars < slen) return NC_ENOTINDEFINE; (void) memcpy(ncstrp->cp, str, slen); diff = ncstrp->nchars - slen; if(diff != 0) (void) memset(ncstrp->cp + slen, 0, diff); return NC_NOERR; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/netcdf.h0000644000175000017500000007366211606020250022112 0ustar amckinstryamckinstry/* * Copyright 1993-2005 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. 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. */ /* "$Id: netcdf.h,v 1.1 2010-01-06 16:34:07 kwleiter Exp $" */ #ifndef _NETCDF_ #define _NETCDF_ #include "vtk_netcdf_mangle.h" #include "ncconfig.h" /* for DLL_NETCDF */ #include /* size_t, ptrdiff_t */ #include /* netcdf functions sometimes return system errors */ #if defined(__cplusplus) extern "C" { #endif /* * The netcdf external data types */ typedef enum { NC_NAT = 0, /* NAT = 'Not A Type' (c.f. NaN) */ NC_BYTE = 1, /* signed 1 byte integer */ NC_CHAR = 2, /* ISO/ASCII character */ NC_SHORT = 3, /* signed 2 byte integer */ NC_INT = 4, /* signed 4 byte integer */ NC_FLOAT = 5, /* single precision floating point number */ NC_DOUBLE = 6 /* double precision floating point number */ } nc_type; /* * Default fill values, used unless _FillValue attribute is set. * These values are stuffed into newly allocated space as appropriate. * The hope is that one might use these to notice that a particular datum * has not been set. */ #define NC_FILL_BYTE ((signed char)-127) #define NC_FILL_CHAR ((char)0) #define NC_FILL_SHORT ((short)-32767) #define NC_FILL_INT (-2147483647L) #define NC_FILL_FLOAT (9.9692099683868690e+36f) /* near 15 * 2^119 */ #define NC_FILL_DOUBLE (9.9692099683868690e+36) /* * The above values are defaults. * If you wish a variable to use a different value than the above * defaults, create an attribute with the same type as the variable * and the following reserved name. The value you give the attribute * will be used as the fill value for that variable. */ #define _FillValue "_FillValue" #define NC_FILL 0 /* argument to ncsetfill to clear NC_NOFILL */ #define NC_NOFILL 0x100 /* Don't fill data section an records */ /* * 'mode' flags for ncopen */ #define NC_NOWRITE 0 /* default is read only */ #define NC_WRITE 0x1 /* read & write */ /* * 'mode' flags for nccreate */ #define NC_CLOBBER 0 #define NC_NOCLOBBER 0x4 /* Don't destroy existing file on create */ #define NC_64BIT_OFFSET 0x0200 /* Use large (64-bit) file offsets */ /* * 'mode' flags for nccreate and ncopen */ #define NC_SHARE 0x0800 /* Share updates, limit cacheing */ #define NC_STRICT_NC3 (0x8) /* The following flag currently is ignored, but use in * nc_open() or nc_create() may someday support use of advisory * locking to prevent multiple writers from clobbering a file */ #define NC_LOCK 0x0400 /* Use locking if available */ /* * Starting with version 3.6, there were two different format netCDF * files. netCDF-4 introduces the third one. */ #define NC_FORMAT_CLASSIC (1) #define NC_FORMAT_64BIT (2) #define NC_FORMAT_NETCDF4 (3) #define NC_FORMAT_NETCDF4_CLASSIC (4) /* create netcdf-4 files, with NC_STRICT_NC3. */ /* * Let nc__create() or nc__open() figure out * as suitable chunk size. */ #define NC_SIZEHINT_DEFAULT 0 /* * In nc__enddef(), align to the chunk size. */ #define NC_ALIGN_CHUNK ((size_t)(-1)) /* * 'size' argument to ncdimdef for an unlimited dimension */ #define NC_UNLIMITED 0L /* * attribute id to put/get a global attribute */ #define NC_GLOBAL -1 /* These are in support of the coordinate axis stuff. */ #define NC_NOAXISTYPE 0 #define NC_LATITUDE 1 #define NC_LONGITUDE 2 #define NC_GEOX 3 #define NC_GEOY 4 #define NC_GEOZ 5 #define NC_HEIGHT_UP 6 #define NC_HEIGHT_DOWN 7 #define NC_PRESSURE 8 #define NC_TIME 9 #define NC_RADAZ 10 #define NC_RADEL 11 #define NC_RADDIST 12 /* * These maximums are enforced by the interface, to facilitate writing * applications and utilities. However, nothing is statically allocated to * these sizes internally. */ #define NC_MAX_DIMS 1024 /* max dimensions per file */ #define NC_MAX_ATTRS 8192 /* max global or per variable attributes */ #define NC_MAX_VARS 8192 /* max variables per file */ #define NC_MAX_NAME 256 /* max length of a name */ #define NC_MAX_VAR_DIMS NC_MAX_DIMS /* max per variable dimensions */ /* * The netcdf version 3 functions all return integer error status. * These are the possible values, in addition to certain * values from the system errno.h. */ #define NC_ISSYSERR(err) ((err) > 0) #define NC_NOERR 0 /* No Error */ #define NC2_ERR (-1) /* Returned for all errors in the v2 API. */ #define NC_EBADID (-33) /* Not a netcdf id */ #define NC_ENFILE (-34) /* Too many netcdfs open */ #define NC_EEXIST (-35) /* netcdf file exists && NC_NOCLOBBER */ #define NC_EINVAL (-36) /* Invalid Argument */ #define NC_EPERM (-37) /* Write to read only */ #define NC_ENOTINDEFINE (-38) /* Operation not allowed in data mode */ #define NC_EINDEFINE (-39) /* Operation not allowed in define mode */ #define NC_EINVALCOORDS (-40) /* Index exceeds dimension bound */ #define NC_EMAXDIMS (-41) /* NC_MAX_DIMS exceeded */ #define NC_ENAMEINUSE (-42) /* String match to name in use */ #define NC_ENOTATT (-43) /* Attribute not found */ #define NC_EMAXATTS (-44) /* NC_MAX_ATTRS exceeded */ #define NC_EBADTYPE (-45) /* Not a netcdf data type */ #define NC_EBADDIM (-46) /* Invalid dimension id or name */ #define NC_EUNLIMPOS (-47) /* NC_UNLIMITED in the wrong index */ #define NC_EMAXVARS (-48) /* NC_MAX_VARS exceeded */ #define NC_ENOTVAR (-49) /* Variable not found */ #define NC_EGLOBAL (-50) /* Action prohibited on NC_GLOBAL varid */ #define NC_ENOTNC (-51) /* Not a netcdf file */ #define NC_ESTS (-52) /* In Fortran, string too short */ #define NC_EMAXNAME (-53) /* NC_MAX_NAME exceeded */ #define NC_EUNLIMIT (-54) /* NC_UNLIMITED size already in use */ #define NC_ENORECVARS (-55) /* nc_rec op when there are no record vars */ #define NC_ECHAR (-56) /* Attempt to convert between text & numbers */ #define NC_EEDGE (-57) /* Start+count exceeds dimension bound */ #define NC_ESTRIDE (-58) /* Illegal stride */ #define NC_EBADNAME (-59) /* Attribute or variable name contains illegal characters */ /* N.B. following must match value in ncx.h */ #define NC_ERANGE (-60) /* Math result not representable */ #define NC_ENOMEM (-61) /* Memory allocation (malloc) failure */ #define NC_EVARSIZE (-62) /* One or more variable sizes violate format constraints */ #define NC_EDIMSIZE (-63) /* Invalid dimension size */ #define NC_ETRUNC (-64) /* File likely truncated or possibly corrupted */ /* * The Interface */ /* Declaration modifiers for DLL support (MSC et al) */ #if defined(DLL_NETCDF) /* define when library is a DLL */ # if defined(vtkNetCDF_EXPORTS) /* define when building the library */ # define MSC_EXTRA __declspec(dllexport) # else # define MSC_EXTRA __declspec(dllimport) # endif #else # define MSC_EXTRA #endif /* Choose 64-bit functions and word sizes where we can and sanity where we can't */ #ifdef _WIN32 # include # if defined(_MSC_VER) && _MSC_VER>=1300 && SIZEOF_SIZE_T>SIZEOF_OFF_T # define NC_LSEEK _lseeki64 # define off_t __int64 # define NC_STAT __stat64 # define NC_STAT_STRUCT __stat64 # define NC_FSTAT _fstat64 # else /* defined(_MSC_VER) && _MSC_VER>=1300 */ # define NC_LSEEK lseek # define NC_STAT stat # define NC_STAT_STRUCT stat # define NC_FSTAT fstat # endif /* defined(_MSC_VER) && _MSC_VER>=1300 */ #else # define NC_LSEEK lseek # define NC_STAT stat # define NC_STAT_STRUCT stat # define NC_FSTAT fstat #endif /* defined(DLL_NETCDF) */ # define EXTERNL MSC_EXTRA extern /* When netCDF is built as a DLL, this will export ncerr and * ncopts. When it is used as a DLL, it will import them. */ EXTERNL int ncerr; EXTERNL int ncopts; EXTERNL const char * nc_inq_libvers(void); EXTERNL const char * nc_strerror(int ncerr_arg); EXTERNL int nc__create(const char *path, int cmode, size_t initialsz, size_t *chunksizehintp, int *ncidp); EXTERNL int nc_create(const char *path, int cmode, int *ncidp); EXTERNL int nc__open(const char *path, int mode, size_t *chunksizehintp, int *ncidp); EXTERNL int nc_open(const char *path, int mode, int *ncidp); EXTERNL int nc_set_fill(int ncid, int fillmode, int *old_modep); EXTERNL int nc_redef(int ncid); EXTERNL int nc__enddef(int ncid, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align); EXTERNL int nc_enddef(int ncid); EXTERNL int nc_sync(int ncid); EXTERNL int nc_abort(int ncid); EXTERNL int nc_close(int ncid); EXTERNL int nc_inq(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *unlimdimidp); EXTERNL int nc_inq_ndims(int ncid, int *ndimsp); EXTERNL int nc_inq_nvars(int ncid, int *nvarsp); EXTERNL int nc_inq_natts(int ncid, int *nattsp); EXTERNL int nc_inq_unlimdim(int ncid, int *unlimdimidp); EXTERNL int nc_set_default_format(int format, int *old_formatp); EXTERNL int nc_inq_format(int ncid, int *formatp); /* Begin _dim */ EXTERNL int nc_def_dim(int ncid, const char *name, size_t len, int *idp); EXTERNL int nc_inq_dimid(int ncid, const char *name, int *idp); EXTERNL int nc_inq_dim(int ncid, int dimid, char *name, size_t *lenp); EXTERNL int nc_inq_dimname(int ncid, int dimid, char *name); EXTERNL int nc_inq_dimlen(int ncid, int dimid, size_t *lenp); EXTERNL int nc_rename_dim(int ncid, int dimid, const char *name); /* End _dim */ /* Begin _att */ EXTERNL int nc_inq_att(int ncid, int varid, const char *name, nc_type *xtypep, size_t *lenp); EXTERNL int nc_inq_attid(int ncid, int varid, const char *name, int *idp); EXTERNL int nc_inq_atttype(int ncid, int varid, const char *name, nc_type *xtypep); EXTERNL int nc_inq_attlen(int ncid, int varid, const char *name, size_t *lenp); EXTERNL int nc_inq_attname(int ncid, int varid, int attnum, char *name); EXTERNL int nc_copy_att(int ncid_in, int varid_in, const char *name, int ncid_out, int varid_out); EXTERNL int nc_rename_att(int ncid, int varid, const char *name, const char *newname); EXTERNL int nc_del_att(int ncid, int varid, const char *name); /* End _att */ /* Begin {put,get}_att */ EXTERNL int nc_put_att(int ncid, int varid, const char *name, nc_type datatype, size_t len, const void *value); EXTERNL int nc_get_att(int ncid, int varid, const char *name, void *value); EXTERNL int nc_put_att_text(int ncid, int varid, const char *name, size_t len, const char *op); EXTERNL int nc_get_att_text(int ncid, int varid, const char *name, char *ip); EXTERNL int nc_put_att_uchar(int ncid, int varid, const char *name, nc_type xtype, size_t len, const unsigned char *op); EXTERNL int nc_get_att_uchar(int ncid, int varid, const char *name, unsigned char *ip); EXTERNL int nc_put_att_schar(int ncid, int varid, const char *name, nc_type xtype, size_t len, const signed char *op); EXTERNL int nc_get_att_schar(int ncid, int varid, const char *name, signed char *ip); EXTERNL int nc_put_att_short(int ncid, int varid, const char *name, nc_type xtype, size_t len, const short *op); EXTERNL int nc_get_att_short(int ncid, int varid, const char *name, short *ip); EXTERNL int nc_put_att_int(int ncid, int varid, const char *name, nc_type xtype, size_t len, const int *op); EXTERNL int nc_get_att_int(int ncid, int varid, const char *name, int *ip); EXTERNL int nc_put_att_long(int ncid, int varid, const char *name, nc_type xtype, size_t len, const long *op); EXTERNL int nc_get_att_long(int ncid, int varid, const char *name, long *ip); EXTERNL int nc_put_att_float(int ncid, int varid, const char *name, nc_type xtype, size_t len, const float *op); EXTERNL int nc_get_att_float(int ncid, int varid, const char *name, float *ip); EXTERNL int nc_put_att_double(int ncid, int varid, const char *name, nc_type xtype, size_t len, const double *op); EXTERNL int nc_get_att_double(int ncid, int varid, const char *name, double *ip); /* End {put,get}_att */ /* Begin _var */ EXTERNL int nc_def_var(int ncid, const char *name, nc_type xtype, int ndims, const int *dimidsp, int *varidp); EXTERNL int nc_inq_var(int ncid, int varid, char *name, nc_type *xtypep, int *ndimsp, int *dimidsp, int *nattsp); EXTERNL int nc_inq_varid(int ncid, const char *name, int *varidp); EXTERNL int nc_inq_varname(int ncid, int varid, char *name); EXTERNL int nc_inq_vartype(int ncid, int varid, nc_type *xtypep); EXTERNL int nc_inq_varndims(int ncid, int varid, int *ndimsp); EXTERNL int nc_inq_vardimid(int ncid, int varid, int *dimidsp); EXTERNL int nc_inq_varnatts(int ncid, int varid, int *nattsp); EXTERNL int nc_rename_var(int ncid, int varid, const char *name); EXTERNL int nc_copy_var(int ncid_in, int varid, int ncid_out); #ifndef ncvarcpy /* support the old name for now */ #define ncvarcpy(ncid_in, varid, ncid_out) ncvarcopy((ncid_in), (varid), (ncid_out)) #endif /* End _var */ /* Begin {put,get}_var1 */ EXTERNL int nc_put_var1(int ncid, int varid, const size_t *indexp, const void *value); EXTERNL int nc_get_var1(int ncid, int varid, const size_t *indexp, void *value); EXTERNL int nc_put_var1_text(int ncid, int varid, const size_t *indexp, const char *op); EXTERNL int nc_get_var1_text(int ncid, int varid, const size_t *indexp, char *ip); EXTERNL int nc_put_var1_uchar(int ncid, int varid, const size_t *indexp, const unsigned char *op); EXTERNL int nc_get_var1_uchar(int ncid, int varid, const size_t *indexp, unsigned char *ip); EXTERNL int nc_put_var1_schar(int ncid, int varid, const size_t *indexp, const signed char *op); EXTERNL int nc_get_var1_schar(int ncid, int varid, const size_t *indexp, signed char *ip); EXTERNL int nc_put_var1_short(int ncid, int varid, const size_t *indexp, const short *op); EXTERNL int nc_get_var1_short(int ncid, int varid, const size_t *indexp, short *ip); EXTERNL int nc_put_var1_int(int ncid, int varid, const size_t *indexp, const int *op); EXTERNL int nc_get_var1_int(int ncid, int varid, const size_t *indexp, int *ip); EXTERNL int nc_put_var1_long(int ncid, int varid, const size_t *indexp, const long *op); EXTERNL int nc_get_var1_long(int ncid, int varid, const size_t *indexp, long *ip); EXTERNL int nc_put_var1_float(int ncid, int varid, const size_t *indexp, const float *op); EXTERNL int nc_get_var1_float(int ncid, int varid, const size_t *indexp, float *ip); EXTERNL int nc_put_var1_double(int ncid, int varid, const size_t *indexp, const double *op); EXTERNL int nc_get_var1_double(int ncid, int varid, const size_t *indexp, double *ip); /* End {put,get}_var1 */ /* Begin {put,get}_vara */ EXTERNL int nc_put_vara(int ncid, int varid, const size_t *start, const size_t *count, const void *value); EXTERNL int nc_get_vara(int ncid, int varid, const size_t *start, const size_t *count, void *value); EXTERNL int nc_put_vara_text(int ncid, int varid, const size_t *startp, const size_t *countp, const char *op); EXTERNL int nc_get_vara_text(int ncid, int varid, const size_t *startp, const size_t *countp, char *ip); EXTERNL int nc_put_vara_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const unsigned char *op); EXTERNL int nc_get_vara_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, unsigned char *ip); EXTERNL int nc_put_vara_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const signed char *op); EXTERNL int nc_get_vara_schar(int ncid, int varid, const size_t *startp, const size_t *countp, signed char *ip); EXTERNL int nc_put_vara_short(int ncid, int varid, const size_t *startp, const size_t *countp, const short *op); EXTERNL int nc_get_vara_short(int ncid, int varid, const size_t *startp, const size_t *countp, short *ip); EXTERNL int nc_put_vara_int(int ncid, int varid, const size_t *startp, const size_t *countp, const int *op); EXTERNL int nc_get_vara_int(int ncid, int varid, const size_t *startp, const size_t *countp, int *ip); EXTERNL int nc_put_vara_long(int ncid, int varid, const size_t *startp, const size_t *countp, const long *op); EXTERNL int nc_get_vara_long(int ncid, int varid, const size_t *startp, const size_t *countp, long *ip); EXTERNL int nc_put_vara_float(int ncid, int varid, const size_t *startp, const size_t *countp, const float *op); EXTERNL int nc_get_vara_float(int ncid, int varid, const size_t *startp, const size_t *countp, float *ip); EXTERNL int nc_put_vara_double(int ncid, int varid, const size_t *startp, const size_t *countp, const double *op); EXTERNL int nc_get_vara_double(int ncid, int varid, const size_t *startp, const size_t *countp, double *ip); /* End {put,get}_vara */ /* Begin {put,get}_vars */ EXTERNL int nc_put_vars(int ncid, int varid, const size_t *start, const size_t *count, const ptrdiff_t *stride, const void * value); EXTERNL int nc_get_vars(int ncid, int varid, const size_t *start, const size_t *count, const ptrdiff_t *stride, void * value); EXTERNL int nc_put_vars_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const char *op); EXTERNL int nc_get_vars_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, char *ip); EXTERNL int nc_put_vars_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const unsigned char *op); EXTERNL int nc_get_vars_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, unsigned char *ip); EXTERNL int nc_put_vars_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const signed char *op); EXTERNL int nc_get_vars_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, signed char *ip); EXTERNL int nc_put_vars_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const short *op); EXTERNL int nc_get_vars_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, short *ip); EXTERNL int nc_put_vars_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const int *op); EXTERNL int nc_get_vars_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, int *ip); EXTERNL int nc_put_vars_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const long *op); EXTERNL int nc_get_vars_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, long *ip); EXTERNL int nc_put_vars_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const float *op); EXTERNL int nc_get_vars_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, float *ip); EXTERNL int nc_put_vars_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const double *op); EXTERNL int nc_get_vars_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, double *ip); /* End {put,get}_vars */ /* Begin {put,get}_varm */ EXTERNL int nc_put_varm(int ncid, int varid, const size_t *start, const size_t *count, const ptrdiff_t *stride, const ptrdiff_t *imapp, const void *value); EXTERNL int nc_get_varm(int ncid, int varid, const size_t *start, const size_t *count, const ptrdiff_t *stride, const ptrdiff_t *imapp, void *value); EXTERNL int nc_put_varm_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const char *op); EXTERNL int nc_get_varm_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, char *ip); EXTERNL int nc_put_varm_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const unsigned char *op); EXTERNL int nc_get_varm_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, unsigned char *ip); EXTERNL int nc_put_varm_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const signed char *op); EXTERNL int nc_get_varm_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, signed char *ip); EXTERNL int nc_put_varm_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const short *op); EXTERNL int nc_get_varm_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, short *ip); EXTERNL int nc_put_varm_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const int *op); EXTERNL int nc_get_varm_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, int *ip); EXTERNL int nc_put_varm_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const long *op); EXTERNL int nc_get_varm_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, long *ip); EXTERNL int nc_put_varm_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const float *op); EXTERNL int nc_get_varm_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, float *ip); EXTERNL int nc_put_varm_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const double *op); EXTERNL int nc_get_varm_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t * imapp, double *ip); /* End {put,get}_varm */ /* Begin {put,get}_var */ EXTERNL int nc_put_var_text(int ncid, int varid, const char *op); EXTERNL int nc_get_var_text(int ncid, int varid, char *ip); EXTERNL int nc_put_var_uchar(int ncid, int varid, const unsigned char *op); EXTERNL int nc_get_var_uchar(int ncid, int varid, unsigned char *ip); EXTERNL int nc_put_var_schar(int ncid, int varid, const signed char *op); EXTERNL int nc_get_var_schar(int ncid, int varid, signed char *ip); EXTERNL int nc_put_var_short(int ncid, int varid, const short *op); EXTERNL int nc_get_var_short(int ncid, int varid, short *ip); EXTERNL int nc_put_var_int(int ncid, int varid, const int *op); EXTERNL int nc_get_var_int(int ncid, int varid, int *ip); EXTERNL int nc_put_var_long(int ncid, int varid, const long *op); EXTERNL int nc_get_var_long(int ncid, int varid, long *ip); EXTERNL int nc_put_var_float(int ncid, int varid, const float *op); EXTERNL int nc_get_var_float(int ncid, int varid, float *ip); EXTERNL int nc_put_var_double(int ncid, int varid, const double *op); EXTERNL int nc_get_var_double(int ncid, int varid, double *ip); #ifdef LOGGING #ifdef DEBUG EXTERNL void nc_exit(void); #endif EXTERNL void nc_set_log_level(int new_level); /* Use this to turn off logging by calling nc_log_level(NC_TURN_OFF_LOGGING) */ #define NC_TURN_OFF_LOGGING (-1) #else /* not LOGGING */ #define nc_set_log_level(e) #endif /* End {put,get}_var */ /* #ifdef _CRAYMPP */ /* * Public interfaces to better support * CRAY multi-processor systems like T3E. * A tip of the hat to NERSC. */ /* * It turns out we need to declare and define * these public interfaces on all platforms * or things get ugly working out the * FORTRAN interface. On !_CRAYMPP platforms, * these functions work as advertised, but you * can only use "processor element" 0. */ EXTERNL int nc__create_mp(const char *path, int cmode, size_t initialsz, int basepe, size_t *chunksizehintp, int *ncidp); EXTERNL int nc__open_mp(const char *path, int mode, int basepe, size_t *chunksizehintp, int *ncidp); EXTERNL int nc_delete(const char * path); EXTERNL int nc_delete_mp(const char * path, int basepe); EXTERNL int nc_set_base_pe(int ncid, int pe); EXTERNL int nc_inq_base_pe(int ncid, int *pe); /* #endif _CRAYMPP */ /* Begin v2.4 backward compatiblity */ /* * defining NO_NETCDF_2 to the preprocessor * turns off backward compatiblity declarations. */ #ifndef NO_NETCDF_2 /* * Backward compatible aliases */ #define FILL_BYTE NC_FILL_BYTE #define FILL_CHAR NC_FILL_CHAR #define FILL_SHORT NC_FILL_SHORT #define FILL_LONG NC_FILL_INT #define FILL_FLOAT NC_FILL_FLOAT #define FILL_DOUBLE NC_FILL_DOUBLE #define MAX_NC_DIMS NC_MAX_DIMS #define MAX_NC_ATTRS NC_MAX_ATTRS #define MAX_NC_VARS NC_MAX_VARS #define MAX_NC_NAME NC_MAX_NAME #define MAX_VAR_DIMS NC_MAX_VAR_DIMS /* * If and when 64 integer types become ubiquitous, * we would like to use NC_LONG for that. * For now, define for backward compatibility. */ #define NC_LONG NC_INT /* * Global error status */ EXTERNL int ncerr; #define NC_ENTOOL NC_EMAXNAME /* Backward compatibility */ #define NC_EXDR (-32) /* */ #define NC_SYSERR (-31) /* * Avoid use of this meaningless macro * Use sysconf(_SC_OPEN_MAX). */ #ifndef MAX_NC_OPEN #define MAX_NC_OPEN 32 #endif /* * Global options variable. * Used to determine behavior of error handler. */ #define NC_FATAL 1 #define NC_VERBOSE 2 EXTERNL int ncopts; /* default is (NC_FATAL | NC_VERBOSE) */ EXTERNL void nc_advise(const char *cdf_routine_name, int err, const char *fmt,...); /* * C data type corresponding to a netCDF NC_LONG argument, * a signed 32 bit object. * * This is the only thing in this file which architecture dependent. */ typedef int nclong; EXTERNL int nctypelen(nc_type datatype); EXTERNL int nccreate(const char* path, int cmode); EXTERNL int ncopen(const char* path, int mode); EXTERNL int ncsetfill(int ncid, int fillmode); EXTERNL int ncredef(int ncid); EXTERNL int ncendef(int ncid); EXTERNL int ncsync(int ncid); EXTERNL int ncabort(int ncid); EXTERNL int ncclose(int ncid); EXTERNL int ncinquire(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *unlimdimp); EXTERNL int ncdimdef(int ncid, const char *name, long len); EXTERNL int ncdimid(int ncid, const char *name); EXTERNL int ncdiminq(int ncid, int dimid, char *name, long *lenp); EXTERNL int ncdimrename(int ncid, int dimid, const char *name); EXTERNL int ncattput(int ncid, int varid, const char *name, nc_type xtype, int len, const void *op); EXTERNL int ncattinq(int ncid, int varid, const char *name, nc_type *xtypep, int *lenp); EXTERNL int ncattget(int ncid, int varid, const char *name, void *ip); EXTERNL int ncattcopy(int ncid_in, int varid_in, const char *name, int ncid_out, int varid_out); EXTERNL int ncattname(int ncid, int varid, int attnum, char *name); EXTERNL int ncattrename(int ncid, int varid, const char *name, const char *newname); EXTERNL int ncattdel(int ncid, int varid, const char *name); EXTERNL int ncvardef(int ncid, const char *name, nc_type xtype, int ndims, const int *dimidsp); EXTERNL int ncvarid(int ncid, const char *name); EXTERNL int ncvarinq(int ncid, int varid, char *name, nc_type *xtypep, int *ndimsp, int *dimidsp, int *nattsp); EXTERNL int ncvarput1(int ncid, int varid, const long *indexp, const void *op); EXTERNL int ncvarget1(int ncid, int varid, const long *indexp, void *ip); EXTERNL int ncvarput(int ncid, int varid, const long *startp, const long *countp, const void *op); EXTERNL int ncvarget(int ncid, int varid, const long *startp, const long *countp, void *ip); EXTERNL int ncvarputs(int ncid, int varid, const long *startp, const long *countp, const long *stridep, const void *op); EXTERNL int ncvargets(int ncid, int varid, const long *startp, const long *countp, const long *stridep, void *ip); EXTERNL int ncvarputg(int ncid, int varid, const long *startp, const long *countp, const long *stridep, const long *imapp, const void *op); EXTERNL int ncvargetg(int ncid, int varid, const long *startp, const long *countp, const long *stridep, const long *imapp, void *ip); EXTERNL int ncvarrename(int ncid, int varid, const char *name); EXTERNL int ncrecinq(int ncid, int *nrecvarsp, int *recvaridsp, long *recsizesp); EXTERNL int ncrecget(int ncid, long recnum, void **datap); EXTERNL int ncrecput(int ncid, long recnum, void *const *datap); /* End v2.4 backward compatiblity */ #endif /*!NO_NETCDF_2*/ #if defined(__cplusplus) } #endif #endif /* _NETCDF_ */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/posixio.c0000644000175000017500000012164111606020250022323 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: posixio.c,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #include "ncconfig.h" #include #include #include #ifndef ENOERR #define ENOERR 0 #endif #ifndef NO_SYS_TYPES_H # include #endif /* NO_SYS_TYPES_H */ #include #include #include #ifdef _MSC_VER /* Microsoft Compilers */ # include /* Take the following warning disable out when NetCDF is updated */ /* to support 64-bit versions of "read" and "write" used below */ /* in "px_pgin" and "px_pgout" */ # ifdef _WIN64 # pragma warning ( disable : 4267 ) # endif #endif #ifdef __BORLANDC__ # include # pragma warn -8004 /* "assigned a value that is never used" */ # pragma warn -8065 /* "Call to function 'XXX' with no prototype" */ #endif #ifdef HAVE_UNISTD_H # include #endif #ifndef SEEK_SET #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2 #endif #include "ncio.h" #include "fbits.h" #include "rnd.h" /* #define INSTRUMENT 1 */ #if INSTRUMENT /* debugging */ #undef NDEBUG #include #include "instr.h" #endif #undef MIN /* system may define MIN somewhere and complain */ #define MIN(mm,nn) (((mm) < (nn)) ? (mm) : (nn)) #if !defined(NDEBUG) && !defined(X_INT_MAX) #define X_INT_MAX 2147483647 #endif #if 0 /* !defined(NDEBUG) && !defined(X_ALIGN) */ #define X_ALIGN 4 #else #undef X_ALIGN #endif /* These are needed on mingw to get a dll to compile. They really * should be provided in sys/stats.h, but what the heck. Let's not be * too picky! */ #ifndef S_IRGRP #define S_IRGRP 0000040 #endif #ifndef S_IROTH #define S_IROTH 0000004 #endif #ifndef S_IWGRP #define S_IWGRP 0000020 #endif #ifndef S_IWOTH #define S_IWOTH 0000002 #endif /* * Define the following for debugging. */ /* #define ALWAYS_NC_SHARE 1 */ /* Begin OS */ #ifndef POSIXIO_DEFAULT_PAGESIZE #define POSIXIO_DEFAULT_PAGESIZE 4096 #endif /* * What is the system pagesize? */ static size_t pagesize(void) { /* Hmm, aren't standards great? */ #if defined(_SC_PAGE_SIZE) && !defined(_SC_PAGESIZE) #define _SC_PAGESIZE _SC_PAGE_SIZE #endif #ifdef _SC_PAGESIZE { const long pgsz = sysconf(_SC_PAGESIZE); if(pgsz > 0) return (size_t) pgsz; /* else, silent in the face of error */ } #elif defined(HAVE_GETPAGESIZE) return (size_t) getpagesize(); #endif return (size_t) POSIXIO_DEFAULT_PAGESIZE; } /* * What is the preferred I/O block size? */ static size_t blksize(int fd) { #if defined(HAVE_ST_BLKSIZE) struct stat sb; if (NC_FSTAT(fd, &sb) > -1) { if(sb.st_blksize >= 8192) return (size_t) sb.st_blksize; return 8192; } /* else, silent in the face of error */ #else (void)fd; #endif return (size_t) 2 * pagesize(); } /* * Sortof like ftruncate, except won't make the * file shorter. */ static int fgrow(const int fd, const off_t len) { struct NC_STAT_STRUCT sb; if (NC_FSTAT(fd, &sb) < 0) return errno; if (len < sb.st_size) return ENOERR; { const long dumb = 0; /* we don't use ftruncate() due to problem with FAT32 file systems */ /* cache current position */ const off_t pos = NC_LSEEK(fd, 0, SEEK_CUR); if(pos < 0) return errno; if (NC_LSEEK(fd, len-sizeof(dumb), SEEK_SET) < 0) return errno; if(write(fd, &dumb, sizeof(dumb)) < 0) return errno; if (NC_LSEEK(fd, pos, SEEK_SET) < 0) return errno; } return ENOERR; } /* * Sortof like ftruncate, except won't make the file shorter. Differs * from fgrow by only writing one byte at designated seek position, if * needed. */ static int fgrow2(const int fd, const off_t len) { struct NC_STAT_STRUCT sb; if (NC_FSTAT(fd, &sb) < 0) return errno; if (len <= sb.st_size) return ENOERR; { const char dumb = 0; /* we don't use ftruncate() due to problem with FAT32 file systems */ /* cache current position */ const off_t pos = NC_LSEEK(fd, 0, SEEK_CUR); if(pos < 0) return errno; if (NC_LSEEK(fd, len-1, SEEK_SET) < 0) return errno; if(write(fd, &dumb, sizeof(dumb)) < 0) return errno; if (NC_LSEEK(fd, pos, SEEK_SET) < 0) return errno; } return ENOERR; } /* End OS */ /* Begin px */ /* The px_ functions are for posix systems, when NC_SHARE is not in effect. */ /* Write out a "page" of data to the file. The size of the page (i.e. the extent) varies. nciop - pointer to the file metadata. offset - where in the file should this page be written. extent - how many bytes should be written. vp - pointer to the data to write. posp - pointer to current position in file, updated after write. */ static int px_pgout(ncio *const nciop, off_t const offset, const size_t extent, void *const vp, off_t *posp) { #ifdef X_ALIGN assert(offset % X_ALIGN == 0); #endif assert(*posp == OFF_NONE || *posp == NC_LSEEK(nciop->fd, 0, SEEK_CUR)); if(*posp != offset) { if(NC_LSEEK(nciop->fd, offset, SEEK_SET) != offset) { return errno; } *posp = offset; } if(write(nciop->fd, vp, extent) != (ssize_t) extent) { return errno; } *posp += extent; return ENOERR; } /* Read in a page of data. nciop - a pointer to the ncio struct for this file. offset - byte offset in file where read starts. extent - the size of the page that will be read. vp - a pointer to where the data will end up. nreadp - returned number of bytes actually read (may be less than extent). posp - pointer to current position in file, updated after read. */ static int px_pgin(ncio *const nciop, off_t const offset, const size_t extent, void *const vp, size_t *nreadp, off_t *posp) { int status; ssize_t nread; #ifdef X_ALIGN assert(offset % X_ALIGN == 0); assert(extent % X_ALIGN == 0); #endif assert(*posp == OFF_NONE || *posp == NC_LSEEK(nciop->fd, 0, SEEK_CUR)); if(*posp != offset) { if(NC_LSEEK(nciop->fd, offset, SEEK_SET) != offset) { status = errno; return status; } *posp = offset; } errno = 0; nread = read(nciop->fd, vp, extent); if(nread != (ssize_t) extent) { status = errno; if(nread == -1 || status != ENOERR) return status; /* else it's okay we read less than asked for */ (void) memset((char *)vp + nread, 0, (ssize_t)extent - nread); } *nreadp = nread; *posp += nread; return ENOERR; } /* This struct is for POSIX systems, with NC_SHARE not in effect. If NC_SHARE is used, see ncio_spx. blksz - block size for reads and writes to file. pos - current read/write position in file. bf_offset - file offset corresponding to start of memory buffer bf_extent - number of bytes in I/O request bf_cnt - number of bytes available in buffer bf_base - pointer to beginning of buffer. bf_rflags - buffer region flags (defined in ncio.h) tell the lock status, read/write permissions, and modification status of regions of data in the buffer. bf_refcount - buffer reference count. slave - used in moves. */ typedef struct ncio_px { size_t blksz; off_t pos; /* buffer */ off_t bf_offset; size_t bf_extent; size_t bf_cnt; void *bf_base; int bf_rflags; int bf_refcount; /* chain for double buffering in px_move */ struct ncio_px *slave; } ncio_px; /*ARGSUSED*/ /* This function indicates the file region starting at offset may be released. This is for POSIX, without NC_SHARE. If called with RGN_MODIFIED flag, sets the modified flag in pxp->bf_rflags and decrements the reference count. pxp - pointer to posix non-share ncio_px struct. offset - file offset for beginning of to region to be released. rflags - only RGN_MODIFIED is relevent to this function, others ignored */ static int px_rel(ncio_px *const pxp, off_t offset, int rflags) { (void)offset; assert(pxp->bf_offset <= offset && offset < pxp->bf_offset + (off_t) pxp->bf_extent); assert(pIf(fIsSet(rflags, RGN_MODIFIED), fIsSet(pxp->bf_rflags, RGN_WRITE))); if(fIsSet(rflags, RGN_MODIFIED)) { fSet(pxp->bf_rflags, RGN_MODIFIED); } pxp->bf_refcount--; return ENOERR; } /* This function indicates the file region starting at offset may be released. Each read or write to the file is bracketed by a call to the "get" region function and a call to the "rel" region function. If you only read from the memory region, release it with a flag of 0, if you modify the region, release it with a flag of RGN_MODIFIED. For POSIX system, without NC_SHARE, this becomes the rel function pointed to by the ncio rel function pointer. It mearly checks for file write permission, then calls px_rel to do everything. nciop - pointer to ncio struct. offset - num bytes from beginning of buffer to region to be released. rflags - only RGN_MODIFIED is relevent to this function, others ignored */ static int ncio_px_rel(ncio *const nciop, off_t offset, int rflags) { ncio_px *const pxp = (ncio_px *)nciop->pvt; if(fIsSet(rflags, RGN_MODIFIED) && !fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ return px_rel(pxp, offset, rflags); } /* POSIX get. This will "make a region available." Since we're using buffered IO, this means that if needed, we'll fetch a new page from the file, otherwise, just return a pointer to what's in memory already. nciop - pointer to ncio struct, containing file info. pxp - pointer to ncio_px struct, which contains special metadate for posix files without NC_SHARE. offset - start byte of region to get. extent - how many bytes to read. rflags - One of the RGN_* flags defined in ncio.h. vpp - pointer to pointer that will recieve data. NOTES: * For blkoffset round offset down to the nearest pxp->blksz. This provides the offset (in bytes) to the beginning of the block that holds the current offset. * diff tells how far into the current block we are. * For blkextent round up to the number of bytes at the beginning of the next block, after the one that holds our current position, plus whatever extra (i.e. the extent) that we are about to grab. * The blkextent can't be more than twice the pxp->blksz. That's because the pxp->blksize is the sizehint, and in ncio_px_init2 the buffer (pointed to by pxp->bf-base) is allocated with 2 * *sizehintp. This is checked (unneccesarily) more than once in asserts. * If this is called on a newly opened file, pxp->bf_offset will be OFF_NONE and we'll jump to label pgin to immediately read in a page. */ static int px_get(ncio *const nciop, ncio_px *const pxp, off_t offset, size_t extent, int rflags, void **const vpp) { int status = ENOERR; const off_t blkoffset = _RNDDOWN(offset, (off_t)pxp->blksz); size_t diff = (size_t)(offset - blkoffset); size_t blkextent = _RNDUP(diff + extent, pxp->blksz); assert(extent != 0); assert(extent < X_INT_MAX); /* sanity check */ assert(offset >= 0); /* sanity check */ if(2 * pxp->blksz < blkextent) return E2BIG; /* TODO: temporary kludge */ if(pxp->bf_offset == OFF_NONE) { /* Uninitialized */ if(pxp->bf_base == NULL) { assert(pxp->bf_extent == 0); assert(blkextent <= 2 * pxp->blksz); pxp->bf_base = malloc(2 * pxp->blksz); if(pxp->bf_base == NULL) return ENOMEM; } goto pgin; } /* else */ assert(blkextent <= 2 * pxp->blksz); if(blkoffset == pxp->bf_offset) { /* hit */ if(blkextent > pxp->bf_extent) { /* page in upper */ void *const middle = (void *)((char *)pxp->bf_base + pxp->blksz); assert(pxp->bf_extent == pxp->blksz); status = px_pgin(nciop, pxp->bf_offset + (off_t)pxp->blksz, pxp->blksz, middle, &pxp->bf_cnt, &pxp->pos); if(status != ENOERR) return status; pxp->bf_extent = 2 * pxp->blksz; pxp->bf_cnt += pxp->blksz; } goto done; } /* else */ if(pxp->bf_extent > pxp->blksz && blkoffset == pxp->bf_offset + (off_t)pxp->blksz) { /* hit in upper half */ if(blkextent == pxp->blksz) { /* all in upper half, no fault needed */ diff += pxp->blksz; goto done; } /* else */ if(pxp->bf_cnt > pxp->blksz) { /* data in upper half */ void *const middle = (void *)((char *)pxp->bf_base + pxp->blksz); assert(pxp->bf_extent == 2 * pxp->blksz); if(fIsSet(pxp->bf_rflags, RGN_MODIFIED)) { /* page out lower half */ assert(pxp->bf_refcount <= 0); status = px_pgout(nciop, pxp->bf_offset, pxp->blksz, pxp->bf_base, &pxp->pos); if(status != ENOERR) return status; } pxp->bf_cnt -= pxp->blksz; /* copy upper half into lower half */ (void) memcpy(pxp->bf_base, middle, pxp->bf_cnt); } pxp->bf_offset = blkoffset; /* pxp->bf_extent = pxp->blksz; */ assert(blkextent == 2 * pxp->blksz); { /* page in upper */ void *const middle = (void *)((char *)pxp->bf_base + pxp->blksz); status = px_pgin(nciop, pxp->bf_offset + (off_t)pxp->blksz, pxp->blksz, middle, &pxp->bf_cnt, &pxp->pos); if(status != ENOERR) return status; pxp->bf_extent = 2 * pxp->blksz; pxp->bf_cnt += pxp->blksz; } goto done; } /* else */ if(blkoffset == pxp->bf_offset - (off_t)pxp->blksz) { /* wants the page below */ void *const middle = (void *)((char *)pxp->bf_base + pxp->blksz); size_t upper_cnt = 0; if(pxp->bf_cnt > pxp->blksz) { /* data in upper half */ assert(pxp->bf_extent == 2 * pxp->blksz); if(fIsSet(pxp->bf_rflags, RGN_MODIFIED)) { /* page out upper half */ assert(pxp->bf_refcount <= 0); status = px_pgout(nciop, pxp->bf_offset + (off_t)pxp->blksz, pxp->bf_cnt - pxp->blksz, middle, &pxp->pos); if(status != ENOERR) return status; } pxp->bf_cnt = pxp->blksz; pxp->bf_extent = pxp->blksz; } if(pxp->bf_cnt > 0) { /* copy lower half into upper half */ (void) memcpy(middle, pxp->bf_base, pxp->blksz); upper_cnt = pxp->bf_cnt; } /* read page below into lower half */ status = px_pgin(nciop, blkoffset, pxp->blksz, pxp->bf_base, &pxp->bf_cnt, &pxp->pos); if(status != ENOERR) return status; pxp->bf_offset = blkoffset; if(upper_cnt != 0) { pxp->bf_extent = 2 * pxp->blksz; pxp->bf_cnt = pxp->blksz + upper_cnt; } else { pxp->bf_extent = pxp->blksz; } goto done; } /* else */ /* no overlap */ if(fIsSet(pxp->bf_rflags, RGN_MODIFIED)) { assert(pxp->bf_refcount <= 0); status = px_pgout(nciop, pxp->bf_offset, pxp->bf_cnt, pxp->bf_base, &pxp->pos); if(status != ENOERR) return status; pxp->bf_rflags = 0; } pgin: status = px_pgin(nciop, blkoffset, blkextent, pxp->bf_base, &pxp->bf_cnt, &pxp->pos); if(status != ENOERR) return status; pxp->bf_offset = blkoffset; pxp->bf_extent = blkextent; done: extent += diff; if(pxp->bf_cnt < extent) pxp->bf_cnt = extent; assert(pxp->bf_cnt <= pxp->bf_extent); pxp->bf_rflags |= rflags; pxp->bf_refcount++; *vpp = (char *)pxp->bf_base + diff; return ENOERR; } /* Request that the region (offset, extent) be made available through *vpp. This function converts a file region specified by an offset and extent to a memory pointer. The region may be locked until the corresponding call to rel(). For POSIX systems, without NC_SHARE. This function gets a page of size extent? This is a wrapper for the function px_get, which does all the heavy lifting. nciop - pointer to ncio struct for this file. offset - offset (from beginning of file?) to the data we want to read. extent - the number of bytes to read from the file. rflags - One of the RGN_* flags defined in ncio.h. vpp - handle to point at data when it's been read. */ static int ncio_px_get(ncio *const nciop, off_t offset, size_t extent, int rflags, void **const vpp) { ncio_px *const pxp = (ncio_px *)nciop->pvt; if(fIsSet(rflags, RGN_WRITE) && !fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ /* reclaim space used in move */ if(pxp->slave != NULL) { if(pxp->slave->bf_base != NULL) { free(pxp->slave->bf_base); pxp->slave->bf_base = NULL; pxp->slave->bf_extent = 0; pxp->slave->bf_offset = OFF_NONE; } free(pxp->slave); pxp->slave = NULL; } return px_get(nciop, pxp, offset, extent, rflags, vpp); } /* ARGSUSED */ static int px_double_buffer(ncio *const nciop, off_t to, off_t from, size_t nbytes, int rflags) { ncio_px *const pxp = (ncio_px *)nciop->pvt; int status = ENOERR; void *src; void *dest; (void)rflags; #if INSTRUMENT fprintf(stderr, "\tdouble_buffr %ld %ld %ld\n", (long)to, (long)from, (long)nbytes); #endif status = px_get(nciop, pxp, to, nbytes, RGN_WRITE, &dest); if(status != ENOERR) return status; if(pxp->slave == NULL) { pxp->slave = (ncio_px *) malloc(sizeof(ncio_px)); if(pxp->slave == NULL) return ENOMEM; pxp->slave->blksz = pxp->blksz; /* pos done below */ pxp->slave->bf_offset = pxp->bf_offset; pxp->slave->bf_extent = pxp->bf_extent; pxp->slave->bf_cnt = pxp->bf_cnt; pxp->slave->bf_base = malloc(2 * pxp->blksz); if(pxp->slave->bf_base == NULL) return ENOMEM; (void) memcpy(pxp->slave->bf_base, pxp->bf_base, pxp->bf_extent); pxp->slave->bf_rflags = 0; pxp->slave->bf_refcount = 0; pxp->slave->slave = NULL; } pxp->slave->pos = pxp->pos; status = px_get(nciop, pxp->slave, from, nbytes, 0, &src); if(status != ENOERR) return status; if(pxp->pos != pxp->slave->pos) { /* position changed, sync */ pxp->pos = pxp->slave->pos; } (void) memcpy(dest, src, nbytes); (void)px_rel(pxp->slave, from, 0); (void)px_rel(pxp, to, RGN_MODIFIED); return status; } /* Like memmove(), safely move possibly overlapping data. Copy one region to another without making anything available to higher layers. May be just implemented in terms of get() and rel(), or may be tricky to be efficient. Only used in by nc_enddef() after redefinition. nciop - pointer to ncio struct with file info. to - src for move? from - dest for move? nbytes - number of bytes to move. rflags - One of the RGN_* flags defined in ncio.h. The only reasonable flag value is RGN_NOLOCK. */ static int ncio_px_move(ncio *const nciop, off_t to, off_t from, size_t nbytes, int rflags) { ncio_px *const pxp = (ncio_px *)nciop->pvt; int status = ENOERR; off_t lower; off_t upper; char *base; size_t diff; size_t extent; if(to == from) return ENOERR; /* NOOP */ if(fIsSet(rflags, RGN_WRITE) && !fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ rflags &= RGN_NOLOCK; /* filter unwanted flags */ if(to > from) { /* growing */ lower = from; upper = to; } else { /* shrinking */ lower = to; upper = from; } diff = (size_t)(upper - lower); extent = diff + nbytes; #if INSTRUMENT fprintf(stderr, "ncio_px_move %ld %ld %ld %ld %ld\n", (long)to, (long)from, (long)nbytes, (long)lower, (long)extent); #endif if(extent > pxp->blksz) { size_t remaining = nbytes; if(to > from) { off_t frm = from + nbytes; off_t toh = to + nbytes; for(;;) { size_t loopextent = MIN(remaining, pxp->blksz); frm -= loopextent; toh -= loopextent; status = px_double_buffer(nciop, toh, frm, loopextent, rflags) ; if(status != ENOERR) return status; remaining -= loopextent; if(remaining == 0) break; /* normal loop exit */ } } else { for(;;) { size_t loopextent = MIN(remaining, pxp->blksz); status = px_double_buffer(nciop, to, from, loopextent, rflags) ; if(status != ENOERR) return status; remaining -= loopextent; if(remaining == 0) break; /* normal loop exit */ to += loopextent; from += loopextent; } } return ENOERR; } #if INSTRUMENT fprintf(stderr, "\tncio_px_move small\n"); #endif status = px_get(nciop, pxp, lower, extent, RGN_WRITE|rflags, (void **)&base); if(status != ENOERR) return status; if(to > from) (void) memmove(base + diff, base, nbytes); else (void) memmove(base, base + diff, nbytes); (void) px_rel(pxp, lower, RGN_MODIFIED); return status; } /* Flush any buffers to disk. May be a no-op on if I/O is unbuffered. This function is used when NC_SHARE is NOT used. */ static int ncio_px_sync(ncio *const nciop) { ncio_px *const pxp = (ncio_px *)nciop->pvt; int status = ENOERR; if(fIsSet(pxp->bf_rflags, RGN_MODIFIED)) { assert(pxp->bf_refcount <= 0); status = px_pgout(nciop, pxp->bf_offset, pxp->bf_cnt, pxp->bf_base, &pxp->pos); if(status != ENOERR) return status; pxp->bf_rflags = 0; } else if (!fIsSet(pxp->bf_rflags, RGN_WRITE)) { /* * The dataset is readonly. Invalidate the buffers so * that the next ncio_px_get() will actually read data. */ pxp->bf_offset = OFF_NONE; pxp->bf_cnt = 0; } return status; } /* Internal function called at close to free up anything hanging off pvt. */ static void ncio_px_free(void *const pvt) { ncio_px *const pxp = (ncio_px *)pvt; if(pxp == NULL) return; if(pxp->slave != NULL) { if(pxp->slave->bf_base != NULL) { free(pxp->slave->bf_base); pxp->slave->bf_base = NULL; pxp->slave->bf_extent = 0; pxp->slave->bf_offset = OFF_NONE; } free(pxp->slave); pxp->slave = NULL; } if(pxp->bf_base != NULL) { free(pxp->bf_base); pxp->bf_base = NULL; pxp->bf_extent = 0; pxp->bf_offset = OFF_NONE; } } /* This is the second half of the ncio initialization. This is called after the file has actually been opened. The most important thing that happens is the allocation of a block of memory at pxp->bf_base. This is going to be twice the size of the chunksizehint (rounded up to the nearest sizeof(double)) passed in from nc__create or nc__open. The rounded chunksizehint (passed in here in sizehintp) is going to be stored as pxp->blksize. According to our "contract" we are not allowed to ask for an extent larger than this chunksize/sizehint/blksize from the ncio get function. nciop - pointer to the ncio struct sizehintp - pointer to a size hint that will be rounded up and passed back to the caller. isNew - true if this is being called from ncio_create for a new file. */ static int ncio_px_init2(ncio *const nciop, size_t *sizehintp, int isNew) { ncio_px *const pxp = (ncio_px *)nciop->pvt; const size_t bufsz = 2 * *sizehintp; assert(nciop->fd >= 0); pxp->blksz = *sizehintp; assert(pxp->bf_base == NULL); /* this is separate allocation because it may grow */ pxp->bf_base = malloc(bufsz); if(pxp->bf_base == NULL) return ENOMEM; /* else */ pxp->bf_cnt = 0; if(isNew) { /* save a read */ pxp->pos = 0; pxp->bf_offset = 0; pxp->bf_extent = bufsz; (void) memset(pxp->bf_base, 0, pxp->bf_extent); } return ENOERR; } /* This is the first of a two-part initialization of the ncio struct. Here the rel, get, move, sync, and free function pointers are set to their POSIX non-NC_SHARE functions (ncio_px_*). The ncio_px struct is also partially initialized. */ static void ncio_px_init(ncio *const nciop) { ncio_px *const pxp = (ncio_px *)nciop->pvt; *((ncio_relfunc **)&nciop->rel) = ncio_px_rel; /* cast away const */ *((ncio_getfunc **)&nciop->get) = ncio_px_get; /* cast away const */ *((ncio_movefunc **)&nciop->move) = ncio_px_move; /* cast away const */ *((ncio_syncfunc **)&nciop->sync) = ncio_px_sync; /* cast away const */ *((ncio_freefunc **)&nciop->free) = ncio_px_free; /* cast away const */ pxp->blksz = 0; pxp->pos = -1; pxp->bf_offset = OFF_NONE; pxp->bf_extent = 0; pxp->bf_rflags = 0; pxp->bf_refcount = 0; pxp->bf_base = NULL; pxp->slave = NULL; } /* Begin spx */ /* This is the struct that gets hung of ncio->pvt(?) when the NC_SHARE flag is used. */ typedef struct ncio_spx { off_t pos; /* buffer */ off_t bf_offset; size_t bf_extent; size_t bf_cnt; void *bf_base; } ncio_spx; /*ARGSUSED*/ /* This function releases the region specified by offset. For POSIX system, with NC_SHARE, this becomes the rel function pointed to by the ncio rel function pointer. It mearly checks for file write permission, then calls px_rel to do everything. nciop - pointer to ncio struct. offset - beginning of region. rflags - One of the RGN_* flags defined in ncio.h. If set to RGN_MODIFIED it means that the data in this region were modified, and it needs to be written out to the disk immediately (since we are not buffering with NC_SHARE on). */ static int ncio_spx_rel(ncio *const nciop, off_t offset, int rflags) { ncio_spx *const pxp = (ncio_spx *)nciop->pvt; int status = ENOERR; (void)offset; assert(pxp->bf_offset <= offset); assert(pxp->bf_cnt != 0); assert(pxp->bf_cnt <= pxp->bf_extent); #ifdef X_ALIGN assert(offset < pxp->bf_offset + X_ALIGN); assert(pxp->bf_cnt % X_ALIGN == 0 ); #endif if(fIsSet(rflags, RGN_MODIFIED)) { if(!fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ status = px_pgout(nciop, pxp->bf_offset, pxp->bf_cnt, pxp->bf_base, &pxp->pos); /* if error, invalidate buffer anyway */ } pxp->bf_offset = OFF_NONE; pxp->bf_cnt = 0; return status; } /* Request that the region (offset, extent) be made available through *vpp. This function converts a file region specified by an offset and extent to a memory pointer. The region may be locked until the corresponding call to rel(). For POSIX systems, with NC_SHARE. nciop - pointer to ncio struct for this file. offset - offset (from beginning of file?) to the data we want to read. extent - the number of bytes we want. rflags - One of the RGN_* flags defined in ncio.h. May be RGN_NOLOCK. vpp - handle to point at data when it's been read. */ static int ncio_spx_get(ncio *const nciop, off_t offset, size_t extent, int rflags, void **const vpp) { ncio_spx *const pxp = (ncio_spx *)nciop->pvt; int status = ENOERR; #ifdef X_ALIGN size_t rem; #endif if(fIsSet(rflags, RGN_WRITE) && !fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ assert(extent != 0); assert(extent < X_INT_MAX); /* sanity check */ assert(pxp->bf_cnt == 0); #ifdef X_ALIGN rem = (size_t)(offset % X_ALIGN); if(rem != 0) { offset -= rem; extent += rem; } { const size_t rndup = extent % X_ALIGN; if(rndup != 0) extent += X_ALIGN - rndup; } assert(offset % X_ALIGN == 0); assert(extent % X_ALIGN == 0); #endif if(pxp->bf_extent < extent) { if(pxp->bf_base != NULL) { free(pxp->bf_base); pxp->bf_base = NULL; pxp->bf_extent = 0; } assert(pxp->bf_extent == 0); pxp->bf_base = malloc(extent); if(pxp->bf_base == NULL) return ENOMEM; pxp->bf_extent = extent; } status = px_pgin(nciop, offset, extent, pxp->bf_base, &pxp->bf_cnt, &pxp->pos); if(status != ENOERR) return status; pxp->bf_offset = offset; if(pxp->bf_cnt < extent) pxp->bf_cnt = extent; #ifdef X_ALIGN *vpp = (char *)pxp->bf_base + rem; #else *vpp = pxp->bf_base; #endif return ENOERR; } #if 0 /*ARGSUSED*/ static int strategy(ncio *const nciop, off_t to, off_t offset, size_t extent, int rflags) { static ncio_spx pxp[1]; int status = ENOERR; #ifdef X_ALIGN size_t rem; #endif assert(extent != 0); assert(extent < X_INT_MAX); /* sanity check */ #if INSTRUMENT fprintf(stderr, "strategy %ld at %ld to %ld\n", (long)extent, (long)offset, (long)to); #endif #ifdef X_ALIGN rem = (size_t)(offset % X_ALIGN); if(rem != 0) { offset -= rem; extent += rem; } { const size_t rndup = extent % X_ALIGN; if(rndup != 0) extent += X_ALIGN - rndup; } assert(offset % X_ALIGN == 0); assert(extent % X_ALIGN == 0); #endif if(pxp->bf_extent < extent) { if(pxp->bf_base != NULL) { free(pxp->bf_base); pxp->bf_base = NULL; pxp->bf_extent = 0; } assert(pxp->bf_extent == 0); pxp->bf_base = malloc(extent); if(pxp->bf_base == NULL) return ENOMEM; pxp->bf_extent = extent; } status = px_pgin(nciop, offset, extent, pxp->bf_base, &pxp->bf_cnt, &pxp->pos); if(status != ENOERR) return status; pxp->bf_offset = to; /* TODO: XALIGN */ if(pxp->bf_cnt < extent) pxp->bf_cnt = extent; status = px_pgout(nciop, pxp->bf_offset, pxp->bf_cnt, pxp->bf_base, &pxp->pos); /* if error, invalidate buffer anyway */ pxp->bf_offset = OFF_NONE; pxp->bf_cnt = 0; return status; } #endif /* Copy one region to another without making anything available to higher layers. May be just implemented in terms of get() and rel(), or may be tricky to be efficient. Only used in by nc_enddef() after redefinition. nciop - pointer to ncio struct for this file. to - dest for move? from - src for move? nbytes - number of bytes to move. rflags - One of the RGN_* flags defined in ncio.h. */ static int ncio_spx_move(ncio *const nciop, off_t to, off_t from, size_t nbytes, int rflags) { int status = ENOERR; off_t lower = from; off_t upper = to; char *base; size_t diff = (size_t)(upper - lower); size_t extent = diff + nbytes; rflags &= RGN_NOLOCK; /* filter unwanted flags */ if(to == from) return ENOERR; /* NOOP */ if(to > from) { /* growing */ lower = from; upper = to; } else { /* shrinking */ lower = to; upper = from; } diff = (size_t)(upper - lower); extent = diff + nbytes; status = ncio_spx_get(nciop, lower, extent, RGN_WRITE|rflags, (void **)&base); if(status != ENOERR) return status; if(to > from) (void) memmove(base + diff, base, nbytes); else (void) memmove(base, base + diff, nbytes); (void) ncio_spx_rel(nciop, lower, RGN_MODIFIED); return status; } /*ARGSUSED*/ /* Flush any buffers to disk. May be a no-op on if I/O is unbuffered. */ static int ncio_spx_sync(ncio *const nciop) { (void)nciop; /* NOOP */ return ENOERR; } static void ncio_spx_free(void *const pvt) { ncio_spx *const pxp = (ncio_spx *)pvt; if(pxp == NULL) return; if(pxp->bf_base != NULL) { free(pxp->bf_base); pxp->bf_base = NULL; pxp->bf_offset = OFF_NONE; pxp->bf_extent = 0; pxp->bf_cnt = 0; } } /* This does the second half of the ncio_spx struct initialization for POSIX systems, with NC_SHARE on. nciop - pointer to ncio struct for this file. File has been opened. sizehintp - pointer to a size which will be rounded up to the nearest 8-byt boundary and then used as the max size "chunk" (or page) to read from the file. */ static int ncio_spx_init2(ncio *const nciop, const size_t *const sizehintp) { ncio_spx *const pxp = (ncio_spx *)nciop->pvt; assert(nciop->fd >= 0); pxp->bf_extent = *sizehintp; assert(pxp->bf_base == NULL); /* this is separate allocation because it may grow */ pxp->bf_base = malloc(pxp->bf_extent); if(pxp->bf_base == NULL) { pxp->bf_extent = 0; return ENOMEM; } /* else */ return ENOERR; } /* First half of init for ncio_spx struct, setting the rel, get, move, snyc, and free function pointers to the NC_SHARE versions of these functions (i.e. the ncio_spx_* functions). */ static void ncio_spx_init(ncio *const nciop) { ncio_spx *const pxp = (ncio_spx *)nciop->pvt; *((ncio_relfunc **)&nciop->rel) = ncio_spx_rel; /* cast away const */ *((ncio_getfunc **)&nciop->get) = ncio_spx_get; /* cast away const */ *((ncio_movefunc **)&nciop->move) = ncio_spx_move; /* cast away const */ *((ncio_syncfunc **)&nciop->sync) = ncio_spx_sync; /* cast away const */ *((ncio_freefunc **)&nciop->free) = ncio_spx_free; /* cast away const */ pxp->pos = -1; pxp->bf_offset = OFF_NONE; pxp->bf_extent = 0; pxp->bf_cnt = 0; pxp->bf_base = NULL; } /* */ /* This will call whatever free function is attached to the free function pointer in ncio. It's called from ncio_close, and from ncio_open and ncio_create when an error occurs that the file metadata must be freed. */ static void ncio_free(ncio *nciop) { if(nciop == NULL) return; if(nciop->free != NULL) nciop->free(nciop->pvt); free(nciop); } /* Create a new ncio struct to hold info about the file. This will create and init the ncio_px or ncio_spx struct (the latter if NC_SHARE is used.) */ static ncio * ncio_new(const char *path, int ioflags) { size_t sz_ncio = M_RNDUP(sizeof(ncio)); size_t sz_path = M_RNDUP(strlen(path) +1); size_t sz_ncio_pvt; ncio *nciop; #if ALWAYS_NC_SHARE /* DEBUG */ fSet(ioflags, NC_SHARE); #endif if(fIsSet(ioflags, NC_SHARE)) sz_ncio_pvt = sizeof(ncio_spx); else sz_ncio_pvt = sizeof(ncio_px); nciop = (ncio *) malloc(sz_ncio + sz_path + sz_ncio_pvt); if(nciop == NULL) return NULL; nciop->ioflags = ioflags; *((int *)&nciop->fd) = -1; /* cast away const */ nciop->path = (char *) ((char *)nciop + sz_ncio); (void) strcpy((char *)nciop->path, path); /* cast away const */ /* cast away const */ *((void **)&nciop->pvt) = (void *)(nciop->path + sz_path); if(fIsSet(ioflags, NC_SHARE)) ncio_spx_init(nciop); else ncio_px_init(nciop); return nciop; } /* Public below this point */ #define NCIO_MINBLOCKSIZE 256 #define NCIO_MAXBLOCKSIZE 268435456 /* sanity check, about X_SIZE_T_MAX/8 */ #ifdef S_IRUSR #define NC_DEFAULT_CREAT_MODE \ (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) /* 0666 */ #else #define NC_DEFAULT_CREAT_MODE 0666 #endif /* Create a file, and the ncio struct to go with it. This funtion is only called from nc__create_mp. path - path of file to create. ioflags - flags from nc_create initialsz - From the netcdf man page: "The argument Iinitialsize sets the initial size of the file at creation time." igeto - igetsz - sizehintp - this eventually goes into pxp->blksz and is the size of a page of data for buffered reads and writes. nciopp - pointer to a pointer that will get location of newly created and inited ncio struct. igetvpp - pointer to pointer which will get the location of ? */ int ncio_create(const char *path, int ioflags, size_t initialsz, off_t igeto, size_t igetsz, size_t *sizehintp, ncio **nciopp, void **const igetvpp) { ncio *nciop; int oflags = (O_RDWR|O_CREAT); int fd; int status; if(initialsz < (size_t)igeto + igetsz) initialsz = (size_t)igeto + igetsz; fSet(ioflags, NC_WRITE); if(path == NULL || *path == 0) return EINVAL; nciop = ncio_new(path, ioflags); if(nciop == NULL) return ENOMEM; if(fIsSet(ioflags, NC_NOCLOBBER)) fSet(oflags, O_EXCL); else fSet(oflags, O_TRUNC); #ifdef O_BINARY fSet(oflags, O_BINARY); #endif #ifdef vms fd = open(path, oflags, NC_DEFAULT_CREAT_MODE, "ctx=stm"); #else /* Should we mess with the mode based on NC_SHARE ?? */ fd = open(path, oflags, NC_DEFAULT_CREAT_MODE); #endif #if 0 (void) fprintf(stderr, "ncio_create(): path=\"%s\"\n", path); (void) fprintf(stderr, "ncio_create(): oflags=0x%x\n", oflags); #endif if(fd < 0) { status = errno; goto unwind_new; } *((int *)&nciop->fd) = fd; /* cast away const */ if(*sizehintp < NCIO_MINBLOCKSIZE || *sizehintp > NCIO_MAXBLOCKSIZE) { /* Use default */ *sizehintp = blksize(fd); } else { *sizehintp = M_RNDUP(*sizehintp); } if(fIsSet(nciop->ioflags, NC_SHARE)) status = ncio_spx_init2(nciop, sizehintp); else status = ncio_px_init2(nciop, sizehintp, 1); if(status != ENOERR) goto unwind_open; if(initialsz != 0) { status = fgrow(fd, (off_t)initialsz); if(status != ENOERR) goto unwind_open; } if(igetsz != 0) { status = nciop->get(nciop, igeto, igetsz, RGN_WRITE, igetvpp); if(status != ENOERR) goto unwind_open; } *nciopp = nciop; return ENOERR; unwind_open: (void) close(fd); /* ?? unlink */ /*FALLTHRU*/ unwind_new: ncio_free(nciop); return status; } /* This function opens the data file. It is only called from nc.c, from nc__open_mp and nc_delete_mp. path - path of data file. ioflags - flags passed into nc_open. igeto - looks like this function can do an initial page get, and igeto is going to be the offset for that. But it appears to be unused igetsz - the size in bytes of initial page get (a.k.a. extent). Not ever used in the library. sizehintp - pointer to sizehint parameter from nc__open or nc__create. This is used to set pxp->blksz. Here's what the man page has to say: "The argument referenced by chunksize controls a space versus time tradeoff, memory allocated in the netcdf library versus number of system calls. Because of internal requirements, the value may not be set to exactly the value requested. The actual value chosen is returned by reference. Using the value NC_SIZEHINT_DEFAULT causes the library to choose a default. How the system choses the default depends on the system. On many systems, the "preferred I/O block size" is available from the stat() system call, struct stat member st_blksize. If this is available it is used. Lacking that, twice the system pagesize is used. Lacking a call to discover the system pagesize, we just set default chunksize to 8192. The chunksize is a property of a given open netcdf descriptor ncid, it is not a persistent property of the netcdf dataset." nciopp - pointer to pointer that will get address of newly created and inited ncio struct. igetvpp - handle to pass back pointer to data from inital page read, if this were ever used, which it isn't. */ int ncio_open(const char *path, int ioflags, off_t igeto, size_t igetsz, size_t *sizehintp, ncio **nciopp, void **const igetvpp) { ncio *nciop; int oflags = fIsSet(ioflags, NC_WRITE) ? O_RDWR : O_RDONLY; int fd; int status; if(path == NULL || *path == 0) return EINVAL; nciop = ncio_new(path, ioflags); if(nciop == NULL) return ENOMEM; #ifdef O_BINARY fSet(oflags, O_BINARY); #endif #ifdef vms fd = open(path, oflags, 0, "ctx=stm"); #else fd = open(path, oflags, 0); #endif if(fd < 0) { status = errno; goto unwind_new; } *((int *)&nciop->fd) = fd; /* cast away const */ if(*sizehintp < NCIO_MINBLOCKSIZE || *sizehintp > NCIO_MAXBLOCKSIZE) { /* Use default */ *sizehintp = blksize(fd); } else { *sizehintp = M_RNDUP(*sizehintp); } if(fIsSet(nciop->ioflags, NC_SHARE)) status = ncio_spx_init2(nciop, sizehintp); else status = ncio_px_init2(nciop, sizehintp, 0); if(status != ENOERR) goto unwind_open; if(igetsz != 0) { status = nciop->get(nciop, igeto, igetsz, 0, igetvpp); if(status != ENOERR) goto unwind_open; } *nciopp = nciop; return ENOERR; unwind_open: (void) close(fd); /*FALLTHRU*/ unwind_new: ncio_free(nciop); return status; } /* * Get file size in bytes. */ int ncio_filesize(ncio *nciop, off_t *filesizep) { struct stat sb; assert(nciop != NULL); if (fstat(nciop->fd, &sb) < 0) return errno; *filesizep = sb.st_size; return ENOERR; } /* * Sync any changes to disk, then truncate or extend file so its size * is length. This is only intended to be called before close, if the * file is open for writing and the actual size does not match the * calculated size, perhaps as the result of having been previously * written in NOFILL mode. */ int ncio_pad_length(ncio *nciop, off_t length) { int status = ENOERR; if(nciop == NULL) return EINVAL; if(!fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ status = nciop->sync(nciop); if(status != ENOERR) return status; status = fgrow2(nciop->fd, length); if(status != ENOERR) return status; return ENOERR; } /* Write out any dirty buffers to disk and ensure that next read will get data from disk. Sync any changes, then close the open file associated with the ncio struct, and free its memory. nciop - pointer to ncio to close. doUnlink - if true, unlink file */ int ncio_close(ncio *nciop, int doUnlink) { int status = ENOERR; if(nciop == NULL) return EINVAL; status = nciop->sync(nciop); (void) close(nciop->fd); if(doUnlink) (void) unlink(nciop->path); ncio_free(nciop); return status; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/ffio.c0000644000175000017500000004440711606020250021560 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: ffio.c,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ /* addition by O. Heudecker, AWI-Bremerhaven, 12.3.1998 */ /* added correction by John Sheldon and Hans Vahlenkamp 15.4.1998*/ #include "ncconfig.h" #include #include #include /* DEBUG */ #include #ifndef ENOERR #define ENOERR 0 #endif #include #include #include #include /* Insertion by O. R. Heudecker, AWI-Bremerhaven 12.3.98 (1 line)*/ #include #include "ncio.h" #include "fbits.h" #include "rnd.h" #if !defined(NDEBUG) && !defined(X_INT_MAX) #define X_INT_MAX 2147483647 #endif #if 0 /* !defined(NDEBUG) && !defined(X_ALIGN) */ #define X_ALIGN 4 #endif #define ALWAYS_NC_SHARE 0 /* DEBUG */ /* Begin OS */ /* * What is the preferred I/O block size? * (This becomes the default *sizehint == ncp->chunk in the higher layers.) * TODO: What is the the best answer here? */ static size_t blksize(int fd) { struct ffc_stat_s sb; struct ffsw sw; if (fffcntl(fd, FC_STAT, &sb, &sw) > -1) { #ifdef __crayx1 if(sb.st_blksize > 0) return (size_t) sb.st_blksize; #else if(sb.st_oblksize > 0) return (size_t) sb.st_oblksize; #endif } /* else, silent in the face of error */ return (size_t) 32768; } /* * Sortof like ftruncate, except won't make the * file shorter. */ static int fgrow(const int fd, const off_t len) { struct ffc_stat_s sb; struct ffsw sw; if (fffcntl(fd, FC_STAT, &sb, &sw) < 0) return errno; if (len < sb.st_size) return ENOERR; { const long dumb = 0; /* cache current position */ const off_t pos = ffseek(fd, 0, SEEK_CUR); if(pos < 0) return errno; if (ffseek(fd, len-sizeof(dumb), SEEK_SET) < 0) return errno; if(ffwrite(fd, (void *)&dumb, sizeof(dumb)) < 0) return errno; if (ffseek(fd, pos, SEEK_SET) < 0) return errno; } /* else */ return ENOERR; } /* * Sortof like ftruncate, except won't make the file shorter. Differs * from fgrow by only writing one byte at designated seek position, if * needed. */ static int fgrow2(const int fd, const off_t len) { struct ffc_stat_s sb; struct ffsw sw; if (fffcntl(fd, FC_STAT, &sb, &sw) < 0) return errno; if (len <= sb.st_size) return ENOERR; { const char dumb = 0; /* we don't use ftruncate() due to problem with FAT32 file systems */ /* cache current position */ const off_t pos = ffseek(fd, 0, SEEK_CUR); if(pos < 0) return errno; if (ffseek(fd, len-1, SEEK_SET) < 0) return errno; if(ffwrite(fd, (void *)&dumb, sizeof(dumb)) < 0) return errno; if (ffseek(fd, pos, SEEK_SET) < 0) return errno; } return ENOERR; } /* End OS */ /* Begin ffio */ static int ffio_pgout(ncio *const nciop, off_t const offset, const size_t extent, const void *const vp, off_t *posp) { #ifdef X_ALIGN assert(offset % X_ALIGN == 0); assert(extent % X_ALIGN == 0); #endif if(*posp != offset) { if(ffseek(nciop->fd, offset, SEEK_SET) != offset) { return errno; } *posp = offset; } if(ffwrite(nciop->fd, vp, extent) != extent) { return errno; } *posp += extent; return ENOERR; } static int ffio_pgin(ncio *const nciop, off_t const offset, const size_t extent, void *const vp, size_t *nreadp, off_t *posp) { int status; ssize_t nread; #ifdef X_ALIGN assert(offset % X_ALIGN == 0); assert(extent % X_ALIGN == 0); #endif if(*posp != offset) { if(ffseek(nciop->fd, offset, SEEK_SET) != offset) { status = errno; return status; } *posp = offset; } errno = 0; nread = ffread(nciop->fd, vp, extent); if(nread != extent) { status = errno; if(nread == -1 || status != ENOERR) return status; /* else it's okay we read 0. */ } *nreadp = nread; *posp += nread; return ENOERR; } /* */ typedef struct ncio_ffio { off_t pos; /* buffer */ off_t bf_offset; size_t bf_extent; size_t bf_cnt; void *bf_base; } ncio_ffio; static int ncio_ffio_rel(ncio *const nciop, off_t offset, int rflags) { ncio_ffio *ffp = (ncio_ffio *)nciop->pvt; int status = ENOERR; assert(ffp->bf_offset <= offset); assert(ffp->bf_cnt != 0); assert(ffp->bf_cnt <= ffp->bf_extent); #ifdef X_ALIGN assert(offset < ffp->bf_offset + X_ALIGN); assert(ffp->bf_cnt % X_ALIGN == 0 ); #endif if(fIsSet(rflags, RGN_MODIFIED)) { if(!fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ status = ffio_pgout(nciop, ffp->bf_offset, ffp->bf_cnt, ffp->bf_base, &ffp->pos); /* if error, invalidate buffer anyway */ } ffp->bf_offset = OFF_NONE; ffp->bf_cnt = 0; return status; } static int ncio_ffio_get(ncio *const nciop, off_t offset, size_t extent, int rflags, void **const vpp) { ncio_ffio *ffp = (ncio_ffio *)nciop->pvt; int status = ENOERR; #ifdef X_ALIGN size_t rem; #endif if(fIsSet(rflags, RGN_WRITE) && !fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ assert(extent != 0); assert(extent < X_INT_MAX); /* sanity check */ assert(ffp->bf_cnt == 0); #ifdef X_ALIGN /* round to seekable boundaries */ rem = offset % X_ALIGN; if(rem != 0) { offset -= rem; extent += rem; } { const size_t rndup = extent % X_ALIGN; if(rndup != 0) extent += X_ALIGN - rndup; } assert(offset % X_ALIGN == 0); assert(extent % X_ALIGN == 0); #endif if(ffp->bf_extent < extent) { if(ffp->bf_base != NULL) { free(ffp->bf_base); ffp->bf_base = NULL; ffp->bf_extent = 0; } assert(ffp->bf_extent == 0); ffp->bf_base = malloc(extent); if(ffp->bf_base == NULL) return ENOMEM; ffp->bf_extent = extent; } status = ffio_pgin(nciop, offset, extent, ffp->bf_base, &ffp->bf_cnt, &ffp->pos); if(status != ENOERR) return status; ffp->bf_offset = offset; if(ffp->bf_cnt < extent) { (void) memset((char *)ffp->bf_base + ffp->bf_cnt, 0, extent - ffp->bf_cnt); ffp->bf_cnt = extent; } #ifdef X_ALIGN *vpp = (char *)ffp->bf_base + rem; #else *vpp = (char *)ffp->bf_base; #endif return ENOERR; } static int ncio_ffio_move(ncio *const nciop, off_t to, off_t from, size_t nbytes, int rflags) { int status = ENOERR; off_t lower = from; off_t upper = to; char *base; size_t diff = upper - lower; size_t extent = diff + nbytes; rflags &= RGN_NOLOCK; /* filter unwanted flags */ if(to == from) return ENOERR; /* NOOP */ if(to > from) { /* growing */ lower = from; upper = to; } else { /* shrinking */ lower = to; upper = from; } diff = upper - lower; extent = diff + nbytes; status = ncio_ffio_get(nciop, lower, extent, RGN_WRITE|rflags, (void **)&base); if(status != ENOERR) return status; if(to > from) (void) memmove(base + diff, base, nbytes); else (void) memmove(base, base + diff, nbytes); (void) ncio_ffio_rel(nciop, lower, RGN_MODIFIED); return status; } #ifdef NOFFFLUSH /* ncio_ffio_sync_noffflush is only needed if the FFIO global layer is * used, because it currently has a bug that causes the PEs to hang * RKO 06/26/98 */ static int ncio_ffio_sync_noffflush(ncio *const nciop) { struct ffc_stat_s si; /* for call to fffcntl() */ struct ffsw ffstatus; /* to return ffsw.sw_error */ /* run some innocuous ffio routine to get if any errno */ if(fffcntl(nciop->fd, FC_STAT, &si, &ffstatus) < 0) return ffstatus.sw_error; return ENOERR; } /* this tests to see if the global FFIO layer is being called for * returns ~0 if it is, else returns 0 */ static int ncio_ffio_global_test(const char *ControlString) { if (strstr(ControlString,"global") != (char *) NULL) { return ~0; } else { return 0; } } #endif static int ncio_ffio_sync(ncio *const nciop) { #ifdef __crayx1 struct ffsw stat; if(ffflush(nciop->fd,&stat) < 0) #else if(ffflush(nciop->fd) < 0) #endif return errno; return ENOERR; } static void ncio_ffio_free(void *const pvt) { ncio_ffio *ffp = (ncio_ffio *)pvt; if(ffp == NULL) return; if(ffp->bf_base != NULL) { free(ffp->bf_base); ffp->bf_base = NULL; ffp->bf_offset = OFF_NONE; ffp->bf_extent = 0; ffp->bf_cnt = 0; } } static int ncio_ffio_init2(ncio *const nciop, size_t *sizehintp) { ncio_ffio *ffp = (ncio_ffio *)nciop->pvt; assert(nciop->fd >= 0); ffp->bf_extent = *sizehintp; assert(ffp->bf_base == NULL); /* this is separate allocation because it may grow */ ffp->bf_base = malloc(ffp->bf_extent); if(ffp->bf_base == NULL) { ffp->bf_extent = 0; return ENOMEM; } /* else */ return ENOERR; } static void ncio_ffio_init(ncio *const nciop) { ncio_ffio *ffp = (ncio_ffio *)nciop->pvt; *((ncio_relfunc **)&nciop->rel) = ncio_ffio_rel; /* cast away const */ *((ncio_getfunc **)&nciop->get) = ncio_ffio_get; /* cast away const */ *((ncio_movefunc **)&nciop->move) = ncio_ffio_move; /* cast away const */ *((ncio_syncfunc **)&nciop->sync) = ncio_ffio_sync; /* cast away const */ *((ncio_freefunc **)&nciop->free) = ncio_ffio_free; /* cast away const */ ffp->pos = -1; ffp->bf_offset = OFF_NONE; ffp->bf_extent = 0; ffp->bf_cnt = 0; ffp->bf_base = NULL; } /* */ static void ncio_free(ncio *nciop) { if(nciop == NULL) return; if(nciop->free != NULL) nciop->free(nciop->pvt); free(nciop); } static ncio * ncio_new(const char *path, int ioflags) { size_t sz_ncio = M_RNDUP(sizeof(ncio)); size_t sz_path = M_RNDUP(strlen(path) +1); size_t sz_ncio_pvt; ncio *nciop; #if ALWAYS_NC_SHARE /* DEBUG */ fSet(ioflags, NC_SHARE); #endif if(fIsSet(ioflags, NC_SHARE)) fprintf(stderr, "NC_SHARE not implemented for ffio\n"); sz_ncio_pvt = sizeof(ncio_ffio); nciop = (ncio *) malloc(sz_ncio + sz_path + sz_ncio_pvt); if(nciop == NULL) return NULL; nciop->ioflags = ioflags; *((int *)&nciop->fd) = -1; /* cast away const */ nciop->path = (char *) ((char *)nciop + sz_ncio); (void) strcpy((char *)nciop->path, path); /* cast away const */ /* cast away const */ *((void **)&nciop->pvt) = (void *)(nciop->path + sz_path); ncio_ffio_init(nciop); return nciop; } /* put all the FFIO assign specific code here * returns a pointer to an internal static char location * which may change when the function is called again * if the returned pointer is NULL this indicates that an error occured * check errno for the netCDF error value */ /* prototype fortran subroutines */ #ifdef __crayx1 void ASNQFILE(const char *filename, const char *attribute, int *istat, int flen, int alen); void ASNFILE(const char *filename, const char *attribute, int *istat, int flen, int alen); #else void ASNQFILE(_fcd filename, _fcd attribute, int *istat); void ASNFILE(_fcd filename, _fcd attribute, int *istat); #endif #define BUFLEN 256 static const char * ncio_ffio_assign(const char *filename) { static char buffer[BUFLEN]; int istat; #ifndef __crayx1 _fcd fnp, fbp; #endif char *envstr; char *xtra_assign; char emptystr='\0'; /* put things into known states */ memset(buffer,'\0',BUFLEN); errno = ENOERR; /* set up Fortran character pointers */ #ifdef __crayx1 ASNQFILE(filename, buffer, &istat, strlen(filename)+1, BUFLEN); #else fnp = _cptofcd((char *)filename, strlen(filename)); fbp = _cptofcd(buffer, BUFLEN); /* see if the user has "assigned" to this file */ ASNQFILE(fnp, fbp, &istat); #endif if (istat == 0) { /* user has already specified an assign */ return buffer; } else if (istat > 0 || istat < -1) { /* error occured */ errno = EINVAL; return (const char *) NULL; } /* istat = -1 -> no assign for file */ envstr = getenv("NETCDF_FFIOSPEC"); if(envstr == (char *) NULL) { envstr = "bufa:336:2"; /* this should be macroized */ } /* Insertion by Olaf Heudecker, AWI-Bremerhaven, 12.8.1998 to allow more versatile FFIO-assigns */ /* this is unnecessary and could have been included * into the NETCDF_FFIOSPEC environment variable */ xtra_assign = getenv("NETCDF_XFFIOSPEC"); if(xtra_assign == (char *) NULL) { xtra_assign=&emptystr; } if (strlen(envstr)+strlen(xtra_assign) + 4 > BUFLEN) { /* Error: AssignCommand too long */ errno=E2BIG; return (const char *) NULL; } (void) sprintf(buffer,"-F %s %s", envstr,xtra_assign); #ifdef __crayx1 ASNFILE(filename, buffer, &istat, strlen(filename)+1, strlen(buffer)+1); #else fbp = _cptofcd(buffer, strlen(buffer)); ASNFILE(fnp, fbp, &istat); #endif if (istat == 0) { /* success */ return buffer; } else { /* error */ errno = EINVAL; return (const char *) NULL; } } /* Public below this point */ /* TODO: Is this reasonable for this platform? */ static const size_t NCIO_MINBLOCKSIZE = 256; static const size_t NCIO_MAXBLOCKSIZE = 268435456; /* sanity check, about X_SIZE_T_MAX/8 */ int ncio_create(const char *path, int ioflags, size_t initialsz, off_t igeto, size_t igetsz, size_t *sizehintp, ncio **nciopp, void **const igetvpp) { ncio *nciop; const char *ControlString; int oflags = (O_RDWR|O_CREAT|O_TRUNC); int fd; int status; struct ffsw stat; if(initialsz < (size_t)igeto + igetsz) initialsz = (size_t)igeto + igetsz; fSet(ioflags, NC_WRITE); if(path == NULL || *path == 0) return EINVAL; nciop = ncio_new(path, ioflags); if(nciop == NULL) return ENOMEM; if ((ControlString = ncio_ffio_assign(path)) == (const char *)NULL) { /* an error occured - just punt */ status = errno; goto unwind_new; } #ifdef NOFFFLUSH /* test whether the global layer is being called for * this file ... if so then can't call FFIO ffflush() * RKO 06/26/98 */ if (strstr(ControlString,"global") != (char *) NULL) { /* use no ffflush version */ *((ncio_syncfunc **)&nciop->sync) = ncio_ffio_sync_noffflush; } #endif if(fIsSet(ioflags, NC_NOCLOBBER)) fSet(oflags, O_EXCL); /* Orig: fd = ffopens(path, oflags, 0666, 0, &stat, ControlString); */ fd = ffopen(path, oflags, 0666, 0, &stat); if(fd < 0) { status = errno; goto unwind_new; } *((int *)&nciop->fd) = fd; /* cast away const */ if(*sizehintp < NCIO_MINBLOCKSIZE || *sizehintp > NCIO_MAXBLOCKSIZE) { /* Use default */ *sizehintp = blksize(fd); } else { *sizehintp = M_RNDUP(*sizehintp); } status = ncio_ffio_init2(nciop, sizehintp); if(status != ENOERR) goto unwind_open; if(initialsz != 0) { status = fgrow(fd, (off_t)initialsz); if(status != ENOERR) goto unwind_open; } if(igetsz != 0) { status = nciop->get(nciop, igeto, igetsz, RGN_WRITE, igetvpp); if(status != ENOERR) goto unwind_open; } *nciopp = nciop; return ENOERR; unwind_open: (void) ffclose(fd); /* ?? unlink */ /*FALLTHRU*/ unwind_new: ncio_free(nciop); return status; } int ncio_open(const char *path, int ioflags, off_t igeto, size_t igetsz, size_t *sizehintp, ncio **nciopp, void **const igetvpp) { ncio *nciop; const char *ControlString; int oflags = fIsSet(ioflags, NC_WRITE) ? O_RDWR : O_RDONLY; int fd; int status; struct ffsw stat; if(path == NULL || *path == 0) return EINVAL; nciop = ncio_new(path, ioflags); if(nciop == NULL) return ENOMEM; if ((ControlString = ncio_ffio_assign(path)) == (const char *)NULL) { /* an error occured - just punt */ status = errno; goto unwind_new; } #ifdef NOFFFLUSH /* test whether the global layer is being called for * this file ... if so then can't call FFIO ffflush() * RKO 06/26/98 */ if (strstr(ControlString,"global") != (char *) NULL) { /* use no ffflush version */ *((ncio_syncfunc **)&nciop->sync) = ncio_ffio_sync_noffflush; } #endif /* Orig: fd = ffopens(path, oflags, 0, 0, &stat, ControlString); */ fd = ffopen(path, oflags, 0, 0, &stat); if(fd < 0) { status = errno; goto unwind_new; } *((int *)&nciop->fd) = fd; /* cast away const */ if(*sizehintp < NCIO_MINBLOCKSIZE || *sizehintp > NCIO_MAXBLOCKSIZE) { /* Use default */ *sizehintp = blksize(fd); } else { *sizehintp = M_RNDUP(*sizehintp); } status = ncio_ffio_init2(nciop, sizehintp); if(status != ENOERR) goto unwind_open; if(igetsz != 0) { status = nciop->get(nciop, igeto, igetsz, 0, igetvpp); if(status != ENOERR) goto unwind_open; } *nciopp = nciop; return ENOERR; unwind_open: (void) ffclose(fd); /*FALLTHRU*/ unwind_new: ncio_free(nciop); return status; } /* * Get file size in bytes. * Is use of ffseek() really necessary, or could we use standard fstat() call * and get st_size member? */ int ncio_filesize(ncio *nciop, off_t *filesizep) { off_t filesize, current, reset; if(nciop == NULL) return EINVAL; current = ffseek(nciop->fd, 0, SEEK_CUR); /* save current */ *filesizep = ffseek(nciop->fd, 0, SEEK_END); /* get size */ reset = ffseek(nciop->fd, current, SEEK_SET); /* reset */ if(reset != current) return EINVAL; return ENOERR; } /* * Sync any changes to disk, then extend file so its size is length. * This is only intended to be called before close, if the file is * open for writing and the actual size does not match the calculated * size, perhaps as the result of having been previously written in * NOFILL mode. */ int ncio_pad_length(ncio *nciop, off_t length) { int status = ENOERR; if(nciop == NULL) return EINVAL; if(!fIsSet(nciop->ioflags, NC_WRITE)) return EPERM; /* attempt to write readonly file */ status = nciop->sync(nciop); if(status != ENOERR) return status; status = fgrow2(nciop->fd, length); if(status != ENOERR) return errno; return ENOERR; } int ncio_close(ncio *nciop, int doUnlink) { /* * TODO: I believe this function is lacking the de-assignment of the * Fortran LUN assigned by ASNFILE in ncio_ffio_assign(...) -- SRE * 2002-07-10. */ int status = ENOERR; if(nciop == NULL) return EINVAL; status = nciop->sync(nciop); (void) ffclose(nciop->fd); if(doUnlink) (void) unlink(nciop->path); ncio_free(nciop); return status; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/libvers.c0000644000175000017500000000137211606020250022275 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: libvers.c,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #include "ncconfig.h" #include "netcdf.h" /* * A version string. This whole function is not needed in netCDF-4, * which has it's own version of this function. */ #ifndef USE_NETCDF4 #define SKIP_LEADING_GARBAGE 33 /* # of chars prior to the actual version */ #define XSTRING(x) #x #define STRING(x) XSTRING(x) static const char nc_libvers[] = "\044Id: \100(#) netcdf library version " STRING(VERSION) " of "__DATE__" "__TIME__" $"; const char * nc_inq_libvers(void) { return &nc_libvers[SKIP_LEADING_GARBAGE]; } #endif /* USE_NETCDF4*/ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/nc.h0000644000175000017500000002073611606020250021241 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: nc.h,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #ifndef _NC_H_ #define _NC_H_ /* * netcdf library 'private' data structures, objects and interfaces */ #include "ncconfig.h" /* If netcdf-4 is in use, rename all nc_ functions to nc3_ functions. */ #ifdef USE_NETCDF4 #include #include #endif #include /* size_t */ #ifndef NO_SYS_TYPES_H # include /* off_t */ #endif /* NO_SYS_TYPES_H */ #include "netcdf.h" #include "ncio.h" /* ncio */ #include "fbits.h" #ifndef NC_ARRAY_GROWBY #define NC_ARRAY_GROWBY 4 #endif /* * The extern size of an empty * netcdf version 1 file. * The initial value of ncp->xsz. */ #define MIN_NC_XSZ 32 typedef struct NC NC; /* forward reference */ /* * The internal data types */ typedef enum { NC_UNSPECIFIED = 0, /* future NC_BITFIELD = 7, */ /* NC_STRING = 8, */ NC_DIMENSION = 10, NC_VARIABLE = 11, NC_ATTRIBUTE = 12 } NCtype; /* * Counted string for names and such */ typedef struct { /* all xdr'd */ size_t nchars; char *cp; } NC_string; /* Begin defined in string.c */ extern void free_NC_string(NC_string *ncstrp); extern int NC_check_name(const char *name); extern NC_string * new_NC_string(size_t slen, const char *str); extern int set_NC_string(NC_string *ncstrp, const char *str); /* End defined in string.c */ /* * NC dimension stucture */ typedef struct { /* all xdr'd */ NC_string *name; size_t size; } NC_dim; typedef struct NC_dimarray { size_t nalloc; /* number allocated >= nelems */ /* below gets xdr'd */ /* NCtype type = NC_DIMENSION */ size_t nelems; /* length of the array */ NC_dim **value; } NC_dimarray; /* Begin defined in dim.c */ extern void free_NC_dim(NC_dim *dimp); extern NC_dim * new_x_NC_dim(NC_string *name); extern int find_NC_Udim(const NC_dimarray *ncap, NC_dim **dimpp); /* dimarray */ extern void free_NC_dimarrayV0(NC_dimarray *ncap); extern void free_NC_dimarrayV(NC_dimarray *ncap); extern int dup_NC_dimarrayV(NC_dimarray *ncap, const NC_dimarray *ref); extern NC_dim * elem_NC_dimarray(const NC_dimarray *ncap, size_t elem); /* End defined in dim.c */ /* * NC attribute */ typedef struct { size_t xsz; /* amount of space at xvalue */ /* below gets xdr'd */ NC_string *name; nc_type type; /* the discriminant */ size_t nelems; /* length of the array */ void *xvalue; /* the actual data, in external representation */ } NC_attr; typedef struct NC_attrarray { size_t nalloc; /* number allocated >= nelems */ /* below gets xdr'd */ /* NCtype type = NC_ATTRIBUTE */ size_t nelems; /* length of the array */ NC_attr **value; } NC_attrarray; /* Begin defined in attr.c */ extern void free_NC_attr(NC_attr *attrp); extern NC_attr * new_x_NC_attr( NC_string *strp, nc_type type, size_t nelems); extern NC_attr ** NC_findattr(const NC_attrarray *ncap, const char *name); /* attrarray */ extern void free_NC_attrarrayV0(NC_attrarray *ncap); extern void free_NC_attrarrayV(NC_attrarray *ncap); extern int dup_NC_attrarrayV(NC_attrarray *ncap, const NC_attrarray *ref); extern NC_attr * elem_NC_attrarray(const NC_attrarray *ncap, size_t elem); /* End defined in attr.c */ /* * NC variable: description and data */ typedef struct { size_t xsz; /* xszof 1 element */ size_t *shape; /* compiled info: dim->size of each dim */ size_t *dsizes; /* compiled info: the right to left product of shape */ /* below gets xdr'd */ NC_string *name; /* next two: formerly NC_iarray *assoc */ /* user definition */ size_t ndims; /* assoc->count */ int *dimids; /* assoc->value */ NC_attrarray attrs; nc_type type; /* the discriminant */ size_t len; /* the total length originally allocated */ off_t begin; } NC_var; typedef struct NC_vararray { size_t nalloc; /* number allocated >= nelems */ /* below gets xdr'd */ /* NCtype type = NC_VARIABLE */ size_t nelems; /* length of the array */ NC_var **value; } NC_vararray; /* Begin defined in var.c */ extern void free_NC_var(NC_var *varp); extern NC_var * new_x_NC_var( NC_string *strp, size_t ndims); /* vararray */ extern void free_NC_vararrayV0(NC_vararray *ncap); extern void free_NC_vararrayV(NC_vararray *ncap); extern int dup_NC_vararrayV(NC_vararray *ncap, const NC_vararray *ref); extern int NC_var_shape(NC_var *varp, const NC_dimarray *dims); extern int NC_findvar(const NC_vararray *ncap, const char *name, NC_var **varpp); extern int NC_check_vlen(NC_var *varp, size_t vlen_max); extern NC_var * NC_lookupvar(NC *ncp, int varid); /* End defined in var.c */ #define IS_RECVAR(vp) \ ((vp)->shape != NULL ? (*(vp)->shape == NC_UNLIMITED) : 0 ) #ifdef LOCKNUMREC /* * typedef SHMEM type * for whenever the SHMEM functions can handle other than shorts */ typedef unsigned short int ushmem_t; typedef short int shmem_t; #endif struct NC { /* links to make list of open netcdf's */ struct NC *next; struct NC *prev; /* contains the previous NC during redef. */ struct NC *old; /* flags */ #define NC_CREAT 2 /* in create phase, cleared by ncendef */ #define NC_INDEF 8 /* in define mode, cleared by ncendef */ #define NC_NSYNC 0x10 /* synchronise numrecs on change */ #define NC_HSYNC 0x20 /* synchronise whole header on change */ #define NC_NDIRTY 0x40 /* numrecs has changed */ #define NC_HDIRTY 0x80 /* header info has changed */ /* NC_NOFILL in netcdf.h, historical interface */ int flags; ncio *nciop; size_t chunk; /* largest extent this layer will request from ncio->get() */ size_t xsz; /* external size of this header, == var[0].begin */ off_t begin_var; /* position of the first (non-record) var */ off_t begin_rec; /* position of the first 'record' */ /* don't constrain maximum size of record unnecessarily */ #if SIZEOF_OFF_T > SIZEOF_SIZE_T off_t recsize; /* length of 'record' */ #else size_t recsize; /* length of 'record' */ #endif /* below gets xdr'd */ size_t numrecs; /* number of 'records' allocated */ NC_dimarray dims; NC_attrarray attrs; NC_vararray vars; #ifdef LOCKNUMREC /* size and named indexes for the lock array protecting NC.numrecs */ # define LOCKNUMREC_DIM 4 # define LOCKNUMREC_VALUE 0 # define LOCKNUMREC_LOCK 1 # define LOCKNUMREC_SERVING 2 # define LOCKNUMREC_BASEPE 3 /* Used on Cray T3E MPP to maintain the * integrity of numrecs for an unlimited dimension */ ushmem_t lock[LOCKNUMREC_DIM]; #endif }; #define NC_readonly(ncp) \ (!fIsSet(ncp->nciop->ioflags, NC_WRITE)) #define NC_IsNew(ncp) \ fIsSet((ncp)->flags, NC_CREAT) #define NC_indef(ncp) \ (NC_IsNew(ncp) || fIsSet((ncp)->flags, NC_INDEF)) #define set_NC_ndirty(ncp) \ fSet((ncp)->flags, NC_NDIRTY) #define NC_ndirty(ncp) \ fIsSet((ncp)->flags, NC_NDIRTY) #define set_NC_hdirty(ncp) \ fSet((ncp)->flags, NC_HDIRTY) #define NC_hdirty(ncp) \ fIsSet((ncp)->flags, NC_HDIRTY) #define NC_dofill(ncp) \ (!fIsSet((ncp)->flags, NC_NOFILL)) #define NC_doHsync(ncp) \ fIsSet((ncp)->flags, NC_HSYNC) #define NC_doNsync(ncp) \ fIsSet((ncp)->flags, NC_NSYNC) #ifndef LOCKNUMREC # define NC_get_numrecs(ncp) \ ((ncp)->numrecs) # define NC_set_numrecs(ncp, nrecs) \ {((ncp)->numrecs = (nrecs));} # define NC_increase_numrecs(ncp, nrecs) \ {if((nrecs) > (ncp)->numrecs) ((ncp)->numrecs = (nrecs));} #else size_t NC_get_numrecs(const NC *ncp); void NC_set_numrecs(NC *ncp, size_t nrecs); void NC_increase_numrecs(NC *ncp, size_t nrecs); #endif /* Begin defined in nc.c */ extern int NC_check_id(int ncid, NC **ncpp); extern int nc_cktype(nc_type datatype); extern size_t ncx_howmany(nc_type type, size_t xbufsize); extern int read_numrecs(NC *ncp); extern int write_numrecs(NC *ncp); extern int NC_sync(NC *ncp); extern int NC_calcsize(NC *ncp, off_t *filesizep); /* End defined in nc.c */ /* Begin defined in v1hpg.c */ extern size_t ncx_len_NC(const NC *ncp, size_t sizeof_off_t); extern int ncx_put_NC(const NC *ncp, void **xpp, off_t offset, size_t extent); extern int nc_get_NC( NC *ncp); /* End defined in v1hpg.c */ /* Begin defined in putget.c */ extern int fill_NC_var(NC *ncp, const NC_var *varp, size_t varsize, size_t recno); extern int nc_inq_rec(int ncid, size_t *nrecvars, int *recvarids, size_t *recsizes); extern int nc_get_rec(int ncid, size_t recnum, void **datap); extern int nc_put_rec(int ncid, size_t recnum, void *const *datap); /* End defined in putget.c */ #endif /* _NC_H_ */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/v1hpg.c0000644000175000017500000007074411606020250021665 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: v1hpg.c,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #include "nc.h" #include #include #include #include #include "rnd.h" #include "ncx.h" /* * This module defines the external representation * of the "header" of a netcdf version one file and * the version two variant that uses 64-bit file * offsets instead of the 32-bit file offsets in version * one files. * For each of the components of the NC structure, * There are (static) ncx_len_XXX(), v1h_put_XXX() * and v1h_get_XXX() functions. These define the * external representation of the components. * The exported entry points for the whole NC structure * are built up from these. */ /* * "magic number" at beginning of file: 0x43444601 (big endian) * assert(sizeof(ncmagic) % X_ALIGN == 0); */ static const schar ncmagic[] = {'C', 'D', 'F', 0x02}; static const schar ncmagic1[] = {'C', 'D', 'F', 0x01}; /* * v1hs == "Version 1 Header Stream" * * The netcdf file version 1 header is * of unknown and potentially unlimited size. * So, we don't know how much to get() on * the initial read. We build a stream, 'v1hs' * on top of ncio to do the header get. */ typedef struct v1hs { ncio *nciop; off_t offset; /* argument to nciop->get() */ size_t extent; /* argument to nciop->get() */ int flags; /* set to RGN_WRITE for write */ int version; /* format variant: NC_FORMAT_CLASSIC or NC_FORMAT_64BIT */ void *base; /* beginning of current buffer */ void *pos; /* current position in buffer */ void *end; /* end of current buffer = base + extent */ } v1hs; /* * Release the stream, invalidate buffer */ static int rel_v1hs(v1hs *gsp) { int status; if(gsp->offset == OFF_NONE || gsp->base == NULL) return ENOERR; status = gsp->nciop->rel(gsp->nciop, gsp->offset, gsp->flags == RGN_WRITE ? RGN_MODIFIED : 0); gsp->end = NULL; gsp->pos = NULL; gsp->base = NULL; return status; } /* * Release the current chunk and get the next one. * Also used for initialization when gsp->base == NULL. */ static int fault_v1hs(v1hs *gsp, size_t extent) { int status; if(gsp->base != NULL) { const ptrdiff_t incr = (char *)gsp->pos - (char *)gsp->base; status = rel_v1hs(gsp); if(status) return status; gsp->offset += incr; } if(extent > gsp->extent) gsp->extent = extent; status = gsp->nciop->get(gsp->nciop, gsp->offset, gsp->extent, gsp->flags, &gsp->base); if(status) return status; gsp->pos = gsp->base; gsp->end = (char *)gsp->base + gsp->extent; return ENOERR; } /* * Ensure that 'nextread' bytes are available. */ static int check_v1hs(v1hs *gsp, size_t nextread) { #if 0 /* DEBUG */ fprintf(stderr, "nextread %lu, remaining %lu\n", (unsigned long)nextread, (unsigned long)((char *)gsp->end - (char *)gsp->pos)); #endif if((char *)gsp->pos + nextread <= (char *)gsp->end) return ENOERR; return fault_v1hs(gsp, nextread); } /* End v1hs */ /* Write a size_t to the header */ static int v1h_put_size_t(v1hs *psp, const size_t *sp) { int status = check_v1hs(psp, X_SIZEOF_SIZE_T); if(status != ENOERR) return status; return ncx_put_size_t(&psp->pos, sp); } /* Read a size_t from the header */ static int v1h_get_size_t(v1hs *gsp, size_t *sp) { int status = check_v1hs(gsp, X_SIZEOF_SIZE_T); if(status != ENOERR) return status; return ncx_get_size_t((const void **)(&gsp->pos), sp); } /* Begin nc_type */ #define X_SIZEOF_NC_TYPE X_SIZEOF_INT /* Write a nc_type to the header */ static int v1h_put_nc_type(v1hs *psp, const nc_type *typep) { const int itype = (int) *typep; int status = check_v1hs(psp, X_SIZEOF_INT); if(status != ENOERR) return status; status = ncx_put_int_int(psp->pos, &itype); psp->pos = (void *)((char *)psp->pos + X_SIZEOF_INT); return status; } /* Read a nc_type from the header */ static int v1h_get_nc_type(v1hs *gsp, nc_type *typep) { int type = 0; int status = check_v1hs(gsp, X_SIZEOF_INT); if(status != ENOERR) return status; status = ncx_get_int_int(gsp->pos, &type); gsp->pos = (void *)((char *)gsp->pos + X_SIZEOF_INT); if(status != ENOERR) return status; assert(type == NC_BYTE || type == NC_CHAR || type == NC_SHORT || type == NC_INT || type == NC_FLOAT || type == NC_DOUBLE); /* else */ *typep = (nc_type) type; return ENOERR; } /* End nc_type */ /* Begin NCtype (internal tags) */ #define X_SIZEOF_NCTYPE X_SIZEOF_INT /* Write a NCtype to the header */ static int v1h_put_NCtype(v1hs *psp, NCtype type) { const int itype = (int) type; int status = check_v1hs(psp, X_SIZEOF_INT); if(status != ENOERR) return status; status = ncx_put_int_int(psp->pos, &itype); psp->pos = (void *)((char *)psp->pos + X_SIZEOF_INT); return status; } /* Read a NCtype from the header */ static int v1h_get_NCtype(v1hs *gsp, NCtype *typep) { int type = 0; int status = check_v1hs(gsp, X_SIZEOF_INT); if(status != ENOERR) return status; status = ncx_get_int_int(gsp->pos, &type); gsp->pos = (void *)((char *)gsp->pos + X_SIZEOF_INT); if(status != ENOERR) return status; /* else */ *typep = (NCtype) type; return ENOERR; } /* End NCtype */ /* Begin NC_string */ /* * How much space will the xdr'd string take. * Formerly NC_xlen_string(cdfstr) */ static size_t ncx_len_NC_string(const NC_string *ncstrp) { size_t sz = X_SIZEOF_SIZE_T; /* nchars */ assert(ncstrp != NULL); if(ncstrp->nchars != 0) { #if 0 assert(ncstrp->nchars % X_ALIGN == 0); sz += ncstrp->nchars; #else sz += _RNDUP(ncstrp->nchars, X_ALIGN); #endif } return sz; } /* Write a NC_string to the header */ static int v1h_put_NC_string(v1hs *psp, const NC_string *ncstrp) { int status; #if 0 assert(ncstrp->nchars % X_ALIGN == 0); #endif status = v1h_put_size_t(psp, &ncstrp->nchars); if(status != ENOERR) return status; status = check_v1hs(psp, _RNDUP(ncstrp->nchars, X_ALIGN)); if(status != ENOERR) return status; status = ncx_pad_putn_text(&psp->pos, ncstrp->nchars, ncstrp->cp); if(status != ENOERR) return status; return ENOERR; } /* Read a NC_string from the header */ static int v1h_get_NC_string(v1hs *gsp, NC_string **ncstrpp) { int status; size_t nchars = 0; NC_string *ncstrp; status = v1h_get_size_t(gsp, &nchars); if(status != ENOERR) return status; ncstrp = new_NC_string(nchars, NULL); if(ncstrp == NULL) { return NC_ENOMEM; } #if 0 /* assert(ncstrp->nchars == nchars || ncstrp->nchars - nchars < X_ALIGN); */ assert(ncstrp->nchars % X_ALIGN == 0); status = check_v1hs(gsp, ncstrp->nchars); #else status = check_v1hs(gsp, _RNDUP(ncstrp->nchars, X_ALIGN)); #endif if(status != ENOERR) goto unwind_alloc; status = ncx_pad_getn_text((const void **)(&gsp->pos), nchars, ncstrp->cp); if(status != ENOERR) goto unwind_alloc; *ncstrpp = ncstrp; return ENOERR; unwind_alloc: free_NC_string(ncstrp); return status; } /* End NC_string */ /* Begin NC_dim */ /* * How much space will the xdr'd dim take. * Formerly NC_xlen_dim(dpp) */ static size_t ncx_len_NC_dim(const NC_dim *dimp) { size_t sz; assert(dimp != NULL); sz = ncx_len_NC_string(dimp->name); sz += X_SIZEOF_SIZE_T; return(sz); } /* Write a NC_dim to the header */ static int v1h_put_NC_dim(v1hs *psp, const NC_dim *dimp) { int status; status = v1h_put_NC_string(psp, dimp->name); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &dimp->size); if(status != ENOERR) return status; return ENOERR; } /* Read a NC_dim from the header */ static int v1h_get_NC_dim(v1hs *gsp, NC_dim **dimpp) { int status; NC_string *ncstrp; NC_dim *dimp; status = v1h_get_NC_string(gsp, &ncstrp); if(status != ENOERR) return status; dimp = new_x_NC_dim(ncstrp); if(dimp == NULL) { status = NC_ENOMEM; goto unwind_name; } status = v1h_get_size_t(gsp, &dimp->size); if(status != ENOERR) { free_NC_dim(dimp); /* frees name */ return status; } *dimpp = dimp; return ENOERR; unwind_name: free_NC_string(ncstrp); return status; } /* How much space in the header is required for this NC_dimarray? */ static size_t ncx_len_NC_dimarray(const NC_dimarray *ncap) { size_t xlen = X_SIZEOF_NCTYPE; /* type */ xlen += X_SIZEOF_SIZE_T; /* count */ if(ncap == NULL) return xlen; /* else */ { const NC_dim **dpp = (const NC_dim **)ncap->value; const NC_dim *const *const end = &dpp[ncap->nelems]; for( /*NADA*/; dpp < end; dpp++) { xlen += ncx_len_NC_dim(*dpp); } } return xlen; } /* Write a NC_dimarray to the header */ static int v1h_put_NC_dimarray(v1hs *psp, const NC_dimarray *ncap) { int status; assert(psp != NULL); if(ncap == NULL #if 1 /* Backward: * This clause is for 'byte for byte' * backward compatibility. * Strickly speaking, it is 'bug for bug'. */ || ncap->nelems == 0 #endif ) { /* * Handle empty netcdf */ const size_t nosz = 0; status = v1h_put_NCtype(psp, NC_UNSPECIFIED); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &nosz); if(status != ENOERR) return status; return ENOERR; } /* else */ status = v1h_put_NCtype(psp, NC_DIMENSION); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &ncap->nelems); if(status != ENOERR) return status; { const NC_dim **dpp = (const NC_dim **)ncap->value; const NC_dim *const *const end = &dpp[ncap->nelems]; for( /*NADA*/; dpp < end; dpp++) { status = v1h_put_NC_dim(psp, *dpp); if(status) return status; } } return ENOERR; } /* Read a NC_dimarray from the header */ static int v1h_get_NC_dimarray(v1hs *gsp, NC_dimarray *ncap) { int status; NCtype type = NC_UNSPECIFIED; assert(gsp != NULL && gsp->pos != NULL); assert(ncap != NULL); assert(ncap->value == NULL); status = v1h_get_NCtype(gsp, &type); if(status != ENOERR) return status; status = v1h_get_size_t(gsp, &ncap->nelems); if(status != ENOERR) return status; if(ncap->nelems == 0) return ENOERR; /* else */ if(type != NC_DIMENSION) return EINVAL; ncap->value = (NC_dim **) malloc(ncap->nelems * sizeof(NC_dim *)); if(ncap->value == NULL) return NC_ENOMEM; ncap->nalloc = ncap->nelems; { NC_dim **dpp = ncap->value; NC_dim *const *const end = &dpp[ncap->nelems]; for( /*NADA*/; dpp < end; dpp++) { status = v1h_get_NC_dim(gsp, dpp); if(status) { ncap->nelems = (size_t)(dpp - ncap->value); free_NC_dimarrayV(ncap); return status; } } } return ENOERR; } /* End NC_dim */ /* Begin NC_attr */ /* * How much space will 'attrp' take in external representation? * Formerly NC_xlen_attr(app) */ static size_t ncx_len_NC_attr(const NC_attr *attrp) { size_t sz; assert(attrp != NULL); sz = ncx_len_NC_string(attrp->name); sz += X_SIZEOF_NC_TYPE; /* type */ sz += X_SIZEOF_SIZE_T; /* nelems */ sz += attrp->xsz; return(sz); } #undef MIN #define MIN(mm,nn) (((mm) < (nn)) ? (mm) : (nn)) /* * Put the values of an attribute * The loop is necessary since attrp->nelems * could potentially be quite large. */ static int v1h_put_NC_attrV(v1hs *psp, const NC_attr *attrp) { int status; const size_t perchunk = psp->extent; size_t remaining = attrp->xsz; void *value = attrp->xvalue; size_t nbytes; assert(psp->extent % X_ALIGN == 0); do { nbytes = MIN(perchunk, remaining); status = check_v1hs(psp, nbytes); if(status != ENOERR) return status; (void) memcpy(psp->pos, value, nbytes); psp->pos = (void *)((char *)psp->pos + nbytes); value = (void *)((char *)value + nbytes); remaining -= nbytes; } while(remaining != 0); return ENOERR; } /* Write a NC_attr to the header */ static int v1h_put_NC_attr(v1hs *psp, const NC_attr *attrp) { int status; status = v1h_put_NC_string(psp, attrp->name); if(status != ENOERR) return status; status = v1h_put_nc_type(psp, &attrp->type); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &attrp->nelems); if(status != ENOERR) return status; status = v1h_put_NC_attrV(psp, attrp); if(status != ENOERR) return status; return ENOERR; } /* * Get the values of an attribute * The loop is necessary since attrp->nelems * could potentially be quite large. */ static int v1h_get_NC_attrV(v1hs *gsp, NC_attr *attrp) { int status; const size_t perchunk = gsp->extent; size_t remaining = attrp->xsz; void *value = attrp->xvalue; size_t nget; do { nget = MIN(perchunk, remaining); status = check_v1hs(gsp, nget); if(status != ENOERR) return status; (void) memcpy(value, gsp->pos, nget); gsp->pos = (void *)((char *)gsp->pos + nget); value = (void *)((char *)value + nget); remaining -= nget; } while(remaining != 0); return ENOERR; } /* Read a NC_attr from the header */ static int v1h_get_NC_attr(v1hs *gsp, NC_attr **attrpp) { NC_string *strp; int status; nc_type type; size_t nelems; NC_attr *attrp; status = v1h_get_NC_string(gsp, &strp); if(status != ENOERR) return status; status = v1h_get_nc_type(gsp, &type); if(status != ENOERR) goto unwind_name; status = v1h_get_size_t(gsp, &nelems); if(status != ENOERR) goto unwind_name; attrp = new_x_NC_attr(strp, type, nelems); if(attrp == NULL) { status = NC_ENOMEM; goto unwind_name; } status = v1h_get_NC_attrV(gsp, attrp); if(status != ENOERR) { free_NC_attr(attrp); /* frees strp */ return status; } *attrpp = attrp; return ENOERR; unwind_name: free_NC_string(strp); return status; } /* How much space in the header is required for this NC_attrarray? */ static size_t ncx_len_NC_attrarray(const NC_attrarray *ncap) { size_t xlen = X_SIZEOF_NCTYPE; /* type */ xlen += X_SIZEOF_SIZE_T; /* count */ if(ncap == NULL) return xlen; /* else */ { const NC_attr **app = (const NC_attr **)ncap->value; const NC_attr *const *const end = &app[ncap->nelems]; for( /*NADA*/; app < end; app++) { xlen += ncx_len_NC_attr(*app); } } return xlen; } /* Write a NC_attrarray to the header */ static int v1h_put_NC_attrarray(v1hs *psp, const NC_attrarray *ncap) { int status; assert(psp != NULL); if(ncap == NULL #if 1 /* Backward: * This clause is for 'byte for byte' * backward compatibility. * Strickly speaking, it is 'bug for bug'. */ || ncap->nelems == 0 #endif ) { /* * Handle empty netcdf */ const size_t nosz = 0; status = v1h_put_NCtype(psp, NC_UNSPECIFIED); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &nosz); if(status != ENOERR) return status; return ENOERR; } /* else */ status = v1h_put_NCtype(psp, NC_ATTRIBUTE); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &ncap->nelems); if(status != ENOERR) return status; { const NC_attr **app = (const NC_attr **)ncap->value; const NC_attr *const *const end = &app[ncap->nelems]; for( /*NADA*/; app < end; app++) { status = v1h_put_NC_attr(psp, *app); if(status) return status; } } return ENOERR; } /* Read a NC_attrarray from the header */ static int v1h_get_NC_attrarray(v1hs *gsp, NC_attrarray *ncap) { int status; NCtype type = NC_UNSPECIFIED; assert(gsp != NULL && gsp->pos != NULL); assert(ncap != NULL); assert(ncap->value == NULL); status = v1h_get_NCtype(gsp, &type); if(status != ENOERR) return status; status = v1h_get_size_t(gsp, &ncap->nelems); if(status != ENOERR) return status; if(ncap->nelems == 0) return ENOERR; /* else */ if(type != NC_ATTRIBUTE) return EINVAL; ncap->value = (NC_attr **) malloc(ncap->nelems * sizeof(NC_attr *)); if(ncap->value == NULL) return NC_ENOMEM; ncap->nalloc = ncap->nelems; { NC_attr **app = ncap->value; NC_attr *const *const end = &app[ncap->nelems]; for( /*NADA*/; app < end; app++) { status = v1h_get_NC_attr(gsp, app); if(status) { ncap->nelems = (size_t)(app - ncap->value); free_NC_attrarrayV(ncap); return status; } } } return ENOERR; } /* End NC_attr */ /* Begin NC_var */ /* * How much space will the xdr'd var take. * Formerly NC_xlen_var(vpp) */ static size_t ncx_len_NC_var(const NC_var *varp, size_t sizeof_off_t) { size_t sz; assert(varp != NULL); assert(sizeof_off_t != 0); sz = ncx_len_NC_string(varp->name); sz += X_SIZEOF_SIZE_T; /* ndims */ sz += ncx_len_int(varp->ndims); /* dimids */ sz += ncx_len_NC_attrarray(&varp->attrs); sz += X_SIZEOF_NC_TYPE; /* type */ sz += X_SIZEOF_SIZE_T; /* len */ sz += sizeof_off_t; /* begin */ return(sz); } /* Write a NC_var to the header */ static int v1h_put_NC_var(v1hs *psp, const NC_var *varp) { int status; status = v1h_put_NC_string(psp, varp->name); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &varp->ndims); if(status != ENOERR) return status; status = check_v1hs(psp, ncx_len_int(varp->ndims)); if(status != ENOERR) return status; status = ncx_putn_int_int(&psp->pos, varp->ndims, varp->dimids); if(status != ENOERR) return status; status = v1h_put_NC_attrarray(psp, &varp->attrs); if(status != ENOERR) return status; status = v1h_put_nc_type(psp, &varp->type); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &varp->len); if(status != ENOERR) return status; status = check_v1hs(psp, psp->version == 1 ? 4 : 8); if(status != ENOERR) return status; status = ncx_put_off_t(&psp->pos, &varp->begin, psp->version == 1 ? 4 : 8); if(status != ENOERR) return status; return ENOERR; } /* Read a NC_var from the header */ static int v1h_get_NC_var(v1hs *gsp, NC_var **varpp) { NC_string *strp; int status; size_t ndims; NC_var *varp; status = v1h_get_NC_string(gsp, &strp); if(status != ENOERR) return status; status = v1h_get_size_t(gsp, &ndims); if(status != ENOERR) goto unwind_name; varp = new_x_NC_var(strp, ndims); if(varp == NULL) { status = NC_ENOMEM; goto unwind_name; } status = check_v1hs(gsp, ncx_len_int(ndims)); if(status != ENOERR) goto unwind_alloc; status = ncx_getn_int_int((const void **)(&gsp->pos), ndims, varp->dimids); if(status != ENOERR) goto unwind_alloc; status = v1h_get_NC_attrarray(gsp, &varp->attrs); if(status != ENOERR) goto unwind_alloc; status = v1h_get_nc_type(gsp, &varp->type); if(status != ENOERR) goto unwind_alloc; status = v1h_get_size_t(gsp, &varp->len); if(status != ENOERR) goto unwind_alloc; status = check_v1hs(gsp, gsp->version == 1 ? 4 : 8); if(status != ENOERR) goto unwind_alloc; status = ncx_get_off_t((const void **)&gsp->pos, &varp->begin, gsp->version == 1 ? 4 : 8); if(status != ENOERR) goto unwind_alloc; *varpp = varp; return ENOERR; unwind_alloc: free_NC_var(varp); /* frees name */ return status; unwind_name: free_NC_string(strp); return status; } /* How much space in the header is required for this NC_vararray? */ static size_t ncx_len_NC_vararray(const NC_vararray *ncap, size_t sizeof_off_t) { size_t xlen = X_SIZEOF_NCTYPE; /* type */ xlen += X_SIZEOF_SIZE_T; /* count */ if(ncap == NULL) return xlen; /* else */ { const NC_var **vpp = (const NC_var **)ncap->value; const NC_var *const *const end = &vpp[ncap->nelems]; for( /*NADA*/; vpp < end; vpp++) { xlen += ncx_len_NC_var(*vpp, sizeof_off_t); } } return xlen; } /* Write a NC_vararray to the header */ static int v1h_put_NC_vararray(v1hs *psp, const NC_vararray *ncap) { int status; assert(psp != NULL); if(ncap == NULL #if 1 /* Backward: * This clause is for 'byte for byte' * backward compatibility. * Strickly speaking, it is 'bug for bug'. */ || ncap->nelems == 0 #endif ) { /* * Handle empty netcdf */ const size_t nosz = 0; status = v1h_put_NCtype(psp, NC_UNSPECIFIED); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &nosz); if(status != ENOERR) return status; return ENOERR; } /* else */ status = v1h_put_NCtype(psp, NC_VARIABLE); if(status != ENOERR) return status; status = v1h_put_size_t(psp, &ncap->nelems); if(status != ENOERR) return status; { const NC_var **vpp = (const NC_var **)ncap->value; const NC_var *const *const end = &vpp[ncap->nelems]; for( /*NADA*/; vpp < end; vpp++) { status = v1h_put_NC_var(psp, *vpp); if(status) return status; } } return ENOERR; } /* Read a NC_vararray from the header */ static int v1h_get_NC_vararray(v1hs *gsp, NC_vararray *ncap) { int status; NCtype type = NC_UNSPECIFIED; assert(gsp != NULL && gsp->pos != NULL); assert(ncap != NULL); assert(ncap->value == NULL); status = v1h_get_NCtype(gsp, &type); if(status != ENOERR) return status; status = v1h_get_size_t(gsp, &ncap->nelems); if(status != ENOERR) return status; if(ncap->nelems == 0) return ENOERR; /* else */ if(type != NC_VARIABLE) return EINVAL; ncap->value = (NC_var **) malloc(ncap->nelems * sizeof(NC_var *)); if(ncap->value == NULL) return NC_ENOMEM; ncap->nalloc = ncap->nelems; { NC_var **vpp = ncap->value; NC_var *const *const end = &vpp[ncap->nelems]; for( /*NADA*/; vpp < end; vpp++) { status = v1h_get_NC_var(gsp, vpp); if(status) { ncap->nelems = (size_t)(vpp - ncap->value); free_NC_vararrayV(ncap); return status; } } } return ENOERR; } /* End NC_var */ /* Begin NC */ /* * Recompute the shapes of all variables * Sets ncp->begin_var to start of first variable. * Sets ncp->begin_rec to start of first record variable. * Returns -1 on error. The only possible error is a reference * to a non existent dimension, which could occur for a corrupted * netcdf file. */ static int NC_computeshapes(NC *ncp) { NC_var **vpp = (NC_var **)ncp->vars.value; NC_var *const *const end = &vpp[ncp->vars.nelems]; NC_var *first_var = NULL; /* first "non-record" var */ NC_var *first_rec = NULL; /* first "record" var */ int status; ncp->begin_var = (off_t) ncp->xsz; ncp->begin_rec = (off_t) ncp->xsz; ncp->recsize = 0; if(ncp->vars.nelems == 0) return(0); for( /*NADA*/; vpp < end; vpp++) { status = NC_var_shape(*vpp, &ncp->dims); if(status != ENOERR) return(status); if(IS_RECVAR(*vpp)) { if(first_rec == NULL) first_rec = *vpp; ncp->recsize += (*vpp)->len; } else { if(first_var == NULL) first_var = *vpp; /* * Overwritten each time thru. * Usually overwritten in first_rec != NULL clause below. */ ncp->begin_rec = (*vpp)->begin + (off_t)(*vpp)->len; } } if(first_rec != NULL) { assert(ncp->begin_rec <= first_rec->begin); ncp->begin_rec = first_rec->begin; /* * for special case of exactly one record variable, pack value */ if(ncp->recsize == first_rec->len) ncp->recsize = *first_rec->dsizes * first_rec->xsz; } if(first_var != NULL) { ncp->begin_var = first_var->begin; } else { ncp->begin_var = ncp->begin_rec; } assert(ncp->begin_var > 0); assert(ncp->xsz <= (size_t)ncp->begin_var); assert(ncp->begin_rec > 0); assert(ncp->begin_var <= ncp->begin_rec); return(ENOERR); } /* How much space in the header is required for the NC data structure? */ size_t ncx_len_NC(const NC *ncp, size_t sizeof_off_t) { size_t xlen = sizeof(ncmagic); assert(ncp != NULL); xlen += X_SIZEOF_SIZE_T; /* numrecs */ xlen += ncx_len_NC_dimarray(&ncp->dims); xlen += ncx_len_NC_attrarray(&ncp->attrs); xlen += ncx_len_NC_vararray(&ncp->vars, sizeof_off_t); return xlen; } /* Write the file header */ int ncx_put_NC(const NC *ncp, void **xpp, off_t offset, size_t extent) { int status; v1hs ps; /* the get stream */ assert(ncp != NULL); /* Initialize stream ps */ ps.nciop = ncp->nciop; ps.flags = RGN_WRITE; if (ncp->flags & NC_64BIT_OFFSET) ps.version = 2; else ps.version = 1; if(xpp == NULL) { /* * Come up with a reasonable stream read size. */ extent = ncp->xsz; if(extent <= MIN_NC_XSZ) { /* first time read */ extent = ncp->chunk; /* Protection for when ncp->chunk is huge; * no need to read hugely. */ if(extent > 4096) extent = 4096; } else if(extent > ncp->chunk) { extent = ncp->chunk; } ps.offset = 0; ps.extent = extent; ps.base = NULL; ps.pos = ps.base; status = fault_v1hs(&ps, extent); if(status) return status; } else { ps.offset = offset; ps.extent = extent; ps.base = *xpp; ps.pos = ps.base; ps.end = (char *)ps.base + ps.extent; } if (ps.version == 2) status = ncx_putn_schar_schar(&ps.pos, sizeof(ncmagic), ncmagic); else status = ncx_putn_schar_schar(&ps.pos, sizeof(ncmagic1), ncmagic1); if(status != ENOERR) goto release; { const size_t nrecs = NC_get_numrecs(ncp); status = ncx_put_size_t(&ps.pos, &nrecs); if(status != ENOERR) goto release; } assert((char *)ps.pos < (char *)ps.end); status = v1h_put_NC_dimarray(&ps, &ncp->dims); if(status != ENOERR) goto release; status = v1h_put_NC_attrarray(&ps, &ncp->attrs); if(status != ENOERR) goto release; status = v1h_put_NC_vararray(&ps, &ncp->vars); if(status != ENOERR) goto release; release: (void) rel_v1hs(&ps); return status; } /* Make the in-memory NC structure from reading the file header */ int nc_get_NC(NC *ncp) { int status; v1hs gs; /* the get stream */ assert(ncp != NULL); /* Initialize stream gs */ gs.nciop = ncp->nciop; gs.offset = 0; /* beginning of file */ gs.extent = 0; gs.flags = 0; gs.version = 0; gs.base = NULL; gs.pos = gs.base; { /* * Come up with a reasonable stream read size. */ off_t filesize; size_t extent; extent = ncp->xsz; if(extent <= MIN_NC_XSZ) { status = ncio_filesize(ncp->nciop, &filesize); if(status) return status; /* first time read */ extent = ncp->chunk; /* Protection for when ncp->chunk is huge; * no need to read hugely. */ if(extent > 4096) extent = 4096; if(extent > (size_t)filesize) extent = filesize; } else if(extent > ncp->chunk) { extent = ncp->chunk; } /* * Invalidate the I/O buffers to force a read of the header * region. */ status = gs.nciop->sync(gs.nciop); if(status) return status; status = fault_v1hs(&gs, extent); if(status) return status; } /* get the header from the stream gs */ { /* Get & check magic number */ schar magic[sizeof(ncmagic)]; (void) memset(magic, 0, sizeof(magic)); status = ncx_getn_schar_schar( (const void **)(&gs.pos), sizeof(magic), magic); if(status != ENOERR) goto unwind_get; if(memcmp(magic, ncmagic, sizeof(ncmagic)-1) != 0) { status = NC_ENOTNC; goto unwind_get; } /* Check version number in last byte of magic */ if (magic[sizeof(ncmagic)-1] == 0x1) { gs.version = 1; } else if (magic[sizeof(ncmagic)-1] == 0x2) { gs.version = 2; fSet(ncp->flags, NC_64BIT_OFFSET); /* Now we support version 2 file access on non-LFS systems -- rkr */ #if 0 if (sizeof(off_t) != 8) { fprintf(stderr, "NETCDF WARNING: Version 2 file on 32-bit system.\n"); } #endif } else { status = NC_ENOTNC; goto unwind_get; } } { size_t nrecs = 0; status = ncx_get_size_t((const void **)(&gs.pos), &nrecs); if(status != ENOERR) goto unwind_get; NC_set_numrecs(ncp, nrecs); } assert((char *)gs.pos < (char *)gs.end); status = v1h_get_NC_dimarray(&gs, &ncp->dims); if(status != ENOERR) goto unwind_get; status = v1h_get_NC_attrarray(&gs, &ncp->attrs); if(status != ENOERR) goto unwind_get; status = v1h_get_NC_vararray(&gs, &ncp->vars); if(status != ENOERR) goto unwind_get; ncp->xsz = ncx_len_NC(ncp, (gs.version == 1) ? 4 : 8); status = NC_computeshapes(ncp); if(status != ENOERR) goto unwind_get; unwind_get: (void) rel_v1hs(&gs); return status; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/attr.c0000644000175000017500000013075211606020250021606 0ustar amckinstryamckinstry/* Do not edit this file. It is produced from the corresponding .m4 source */ /* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: attr.c,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #include "nc.h" #include #include #include #include "ncx.h" #include "fbits.h" #include "rnd.h" #if defined(_MSC_VER) && (_MSC_VER >= 1400) # pragma warning ( disable : 4130 ) /* logical operation on address of string constant */ #endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ /* * Free attr * Formerly NC_free_attr() */ void free_NC_attr(NC_attr *attrp) { if(attrp == NULL) return; free_NC_string(attrp->name); free(attrp); } /* * How much space will 'nelems' of 'type' take in * external representation (as the values of an attribute)? */ static size_t ncx_len_NC_attrV(nc_type type, size_t nelems) { switch(type) { case NC_BYTE: case NC_CHAR: return ncx_len_char(nelems); case NC_SHORT: return ncx_len_short(nelems); case NC_INT: return ncx_len_int(nelems); case NC_FLOAT: return ncx_len_float(nelems); case NC_DOUBLE: return ncx_len_double(nelems); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } /* default */ assert("ncx_len_NC_attr bad type" == 0); return 0; } NC_attr * new_x_NC_attr( NC_string *strp, nc_type type, size_t nelems) { NC_attr *attrp; const size_t xsz = ncx_len_NC_attrV(type, nelems); size_t sz = M_RNDUP(sizeof(NC_attr)); assert(!(xsz == 0 && nelems != 0)); sz += xsz; attrp = (NC_attr *) malloc(sz); if(attrp == NULL ) return NULL; attrp->xsz = xsz; attrp->name = strp; attrp->type = type; attrp->nelems = nelems; if(xsz != 0) attrp->xvalue = (char *)attrp + M_RNDUP(sizeof(NC_attr)); else attrp->xvalue = NULL; return(attrp); } /* * Formerly NC_new_attr(name,type,count,value) */ static NC_attr * new_NC_attr( const char *name, nc_type type, size_t nelems) { NC_string *strp; NC_attr *attrp; assert(name != NULL && *name != 0); strp = new_NC_string(strlen(name), name); if(strp == NULL) return NULL; attrp = new_x_NC_attr(strp, type, nelems); if(attrp == NULL) { free_NC_string(strp); return NULL; } return(attrp); } static NC_attr * dup_NC_attr(const NC_attr *rattrp) { NC_attr *attrp = new_NC_attr(rattrp->name->cp, rattrp->type, rattrp->nelems); if(attrp == NULL) return NULL; (void) memcpy(attrp->xvalue, rattrp->xvalue, rattrp->xsz); return attrp; } /* attrarray */ /* * Free the stuff "in" (referred to by) an NC_attrarray. * Leaves the array itself allocated. */ void free_NC_attrarrayV0(NC_attrarray *ncap) { assert(ncap != NULL); if(ncap->nelems == 0) return; assert(ncap->value != NULL); { NC_attr **app = ncap->value; NC_attr *const *const end = &app[ncap->nelems]; for( /*NADA*/; app < end; app++) { free_NC_attr(*app); *app = NULL; } } ncap->nelems = 0; } /* * Free NC_attrarray values. * formerly NC_free_array() */ void free_NC_attrarrayV(NC_attrarray *ncap) { assert(ncap != NULL); if(ncap->nalloc == 0) return; assert(ncap->value != NULL); free_NC_attrarrayV0(ncap); free(ncap->value); ncap->value = NULL; ncap->nalloc = 0; } int dup_NC_attrarrayV(NC_attrarray *ncap, const NC_attrarray *ref) { int status = NC_NOERR; assert(ref != NULL); assert(ncap != NULL); if(ref->nelems != 0) { const size_t sz = ref->nelems * sizeof(NC_attr *); ncap->value = (NC_attr **) malloc(sz); if(ncap->value == NULL) return NC_ENOMEM; (void) memset(ncap->value, 0, sz); ncap->nalloc = ref->nelems; } ncap->nelems = 0; { NC_attr **app = ncap->value; const NC_attr **drpp = (const NC_attr **)ref->value; NC_attr *const *const end = &app[ref->nelems]; for( /*NADA*/; app < end; drpp++, app++, ncap->nelems++) { *app = dup_NC_attr(*drpp); if(*app == NULL) { status = NC_ENOMEM; break; } } } if(status != NC_NOERR) { free_NC_attrarrayV(ncap); return status; } assert(ncap->nelems == ref->nelems); return NC_NOERR; } /* * Add a new handle on the end of an array of handles * Formerly NC_incr_array(array, tail) */ static int incr_NC_attrarray(NC_attrarray *ncap, NC_attr *newelemp) { NC_attr **vp; assert(ncap != NULL); if(ncap->nalloc == 0) { assert(ncap->nelems == 0); vp = (NC_attr **) malloc(NC_ARRAY_GROWBY * sizeof(NC_attr *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc = NC_ARRAY_GROWBY; } else if(ncap->nelems +1 > ncap->nalloc) { vp = (NC_attr **) realloc(ncap->value, (ncap->nalloc + NC_ARRAY_GROWBY) * sizeof(NC_attr *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc += NC_ARRAY_GROWBY; } if(newelemp != NULL) { ncap->value[ncap->nelems] = newelemp; ncap->nelems++; } return NC_NOERR; } NC_attr * elem_NC_attrarray(const NC_attrarray *ncap, size_t elem) { assert(ncap != NULL); /* cast needed for braindead systems with signed size_t */ if(ncap->nelems == 0 || (unsigned long) elem >= ncap->nelems) return NULL; assert(ncap->value != NULL); return ncap->value[elem]; } /* End attarray per se */ /* * Given ncp and varid, return ptr to array of attributes * else NULL on error */ static NC_attrarray * NC_attrarray0( NC *ncp, int varid) { NC_attrarray *ap; if(varid == NC_GLOBAL) /* Global attribute, attach to cdf */ { ap = &ncp->attrs; } else if(varid >= 0 && (size_t) varid < ncp->vars.nelems) { NC_var **vpp; vpp = (NC_var **)ncp->vars.value; vpp += varid; ap = &(*vpp)->attrs; } else { ap = NULL; } return(ap); } /* * Step thru NC_ATTRIBUTE array, seeking match on name. * return match or NULL if Not Found. */ NC_attr ** NC_findattr(const NC_attrarray *ncap, const char *name) { NC_attr **attrpp; size_t attrid; size_t slen; assert(ncap != NULL); if(ncap->nelems == 0) return NULL; attrpp = (NC_attr **) ncap->value; slen = strlen(name); for(attrid = 0; attrid < ncap->nelems; attrid++, attrpp++) { if(strlen((*attrpp)->name->cp) == slen && strncmp((*attrpp)->name->cp, name, slen) == 0) { return(attrpp); /* Normal return */ } } return(NULL); } /* * Look up by ncid, varid and name, return NULL if not found */ static int NC_lookupattr(int ncid, int varid, const char *name, /* attribute name */ NC_attr **attrpp) /* modified on return */ { int status; NC *ncp; NC_attrarray *ncap; NC_attr **tmp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; tmp = NC_findattr(ncap, name); if(tmp == NULL) return NC_ENOTATT; if(attrpp != NULL) *attrpp = *tmp; return ENOERR; } /* Public */ int nc_inq_attname(int ncid, int varid, int attnum, char *name) { int status; NC *ncp; NC_attrarray *ncap; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; attrp = elem_NC_attrarray(ncap, (size_t)attnum); if(attrp == NULL) return NC_ENOTATT; (void) strncpy(name, attrp->name->cp, attrp->name->nchars); name[attrp->name->nchars] = 0; return NC_NOERR; } int nc_inq_attid(int ncid, int varid, const char *name, int *attnump) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; attrpp = NC_findattr(ncap, name); if(attrpp == NULL) return NC_ENOTATT; if(attnump != NULL) *attnump = (int)(attrpp - ncap->value); return NC_NOERR; } int nc_inq_atttype(int ncid, int varid, const char *name, nc_type *datatypep) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(datatypep != NULL) *datatypep = attrp->type; return NC_NOERR; } int nc_inq_attlen(int ncid, int varid, const char *name, size_t *lenp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(lenp != NULL) *lenp = attrp->nelems; return NC_NOERR; } int nc_inq_att(int ncid, int varid, const char *name, /* input, attribute name */ nc_type *datatypep, size_t *lenp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(datatypep != NULL) *datatypep = attrp->type; if(lenp != NULL) *lenp = attrp->nelems; return NC_NOERR; } int nc_rename_att( int ncid, int varid, const char *name, const char *newname) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **tmp; NC_attr *attrp; NC_string *newStr, *old; /* sortof inline clone of NC_lookupattr() */ status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = NC_check_name(newname); if(status != NC_NOERR) return status; tmp = NC_findattr(ncap, name); if(tmp == NULL) return NC_ENOTATT; attrp = *tmp; /* end inline clone NC_lookupattr() */ if(NC_findattr(ncap, newname) != NULL) { /* name in use */ return NC_ENAMEINUSE; } old = attrp->name; if(NC_indef(ncp)) { newStr = new_NC_string(strlen(newname), newname); if( newStr == NULL) return NC_ENOMEM; attrp->name = newStr; free_NC_string(old); return NC_NOERR; } /* else */ status = set_NC_string(old, newname); if( status != NC_NOERR) return status; set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } int nc_copy_att(int ncid_in, int varid_in, const char *name, int ncid_out, int ovarid) { int status; NC_attr *iattrp; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_lookupattr(ncid_in, varid_in, name, &iattrp); if(status != NC_NOERR) return status; status = NC_check_id(ncid_out, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, ovarid); if(ncap == NULL) return NC_ENOTVAR; attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { attrp = *attrpp; /* convenience */ if(iattrp->xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = iattrp->xsz; attrp->type = iattrp->type; attrp->nelems = iattrp->nelems; (void) memcpy(attrp->xvalue, iattrp->xvalue, iattrp->xsz); set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } attrp = new_NC_attr(name, iattrp->type, iattrp->nelems); if(attrp == NULL) return NC_ENOMEM; (void) memcpy(attrp->xvalue, iattrp->xvalue, iattrp->xsz); if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { status = incr_NC_attrarray(ncap, attrp); if(status != NC_NOERR) { free_NC_attr(attrp); return status; } } return NC_NOERR; } int nc_del_att(int ncid, int varid, const char *name) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; int attrid; size_t slen; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(!NC_indef(ncp)) return NC_ENOTINDEFINE; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; /* sortof inline NC_findattr() */ slen = strlen(name); attrpp = (NC_attr **) ncap->value; for(attrid = 0; (size_t) attrid < ncap->nelems; attrid++, attrpp++) { if( slen == (*attrpp)->name->nchars && strncmp(name, (*attrpp)->name->cp, slen) == 0) { old = *attrpp; break; } } if( (size_t) attrid == ncap->nelems ) return NC_ENOTATT; /* end inline NC_findattr() */ /* shuffle down */ for(attrid++; (size_t) attrid < ncap->nelems; attrid++) { *attrpp = *(attrpp + 1); attrpp++; } *attrpp = NULL; /* decrement count */ ncap->nelems--; free_NC_attr(old); return NC_NOERR; } static int ncx_pad_putn_Iuchar(void **xpp, size_t nelems, const uchar *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_uchar(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_uchar(xpp, nelems, tp); case NC_INT: return ncx_putn_int_uchar(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_uchar(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_uchar(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_Iuchar invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_getn_Iuchar(const void **xpp, size_t nelems, uchar *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_uchar(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_uchar(xpp, nelems, tp); case NC_INT: return ncx_getn_int_uchar(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_uchar(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_uchar(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_Iuchar invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_putn_Ischar(void **xpp, size_t nelems, const schar *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_schar(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_schar(xpp, nelems, tp); case NC_INT: return ncx_putn_int_schar(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_schar(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_schar(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_Ischar invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_getn_Ischar(const void **xpp, size_t nelems, schar *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_schar(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_schar(xpp, nelems, tp); case NC_INT: return ncx_getn_int_schar(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_schar(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_schar(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_Ischar invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_putn_Ishort(void **xpp, size_t nelems, const short *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_short(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_short(xpp, nelems, tp); case NC_INT: return ncx_putn_int_short(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_short(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_short(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_Ishort invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_getn_Ishort(const void **xpp, size_t nelems, short *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_short(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_short(xpp, nelems, tp); case NC_INT: return ncx_getn_int_short(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_short(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_short(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_Ishort invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_putn_Iint(void **xpp, size_t nelems, const int *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_int(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_int(xpp, nelems, tp); case NC_INT: return ncx_putn_int_int(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_int(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_int(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_Iint invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_getn_Iint(const void **xpp, size_t nelems, int *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_int(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_int(xpp, nelems, tp); case NC_INT: return ncx_getn_int_int(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_int(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_int(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_Iint invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_putn_Ilong(void **xpp, size_t nelems, const long *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_long(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_long(xpp, nelems, tp); case NC_INT: return ncx_putn_int_long(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_long(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_long(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_Ilong invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_getn_Ilong(const void **xpp, size_t nelems, long *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_long(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_long(xpp, nelems, tp); case NC_INT: return ncx_getn_int_long(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_long(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_long(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_Ilong invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_putn_Ifloat(void **xpp, size_t nelems, const float *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_float(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_float(xpp, nelems, tp); case NC_INT: return ncx_putn_int_float(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_float(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_float(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_Ifloat invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_getn_Ifloat(const void **xpp, size_t nelems, float *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_float(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_float(xpp, nelems, tp); case NC_INT: return ncx_getn_int_float(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_float(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_float(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_Ifloat invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_putn_Idouble(void **xpp, size_t nelems, const double *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_double(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_double(xpp, nelems, tp); case NC_INT: return ncx_putn_int_double(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_double(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_double(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_Idouble invalid type" == 0); return NC_EBADTYPE; } static int ncx_pad_getn_Idouble(const void **xpp, size_t nelems, double *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_double(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_double(xpp, nelems, tp); case NC_INT: return ncx_getn_int_double(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_double(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_double(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_Idouble invalid type" == 0); return NC_EBADTYPE; } int nc_put_att_text(int ncid, int varid, const char *name, size_t nelems, const char *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = NC_check_name(name); if(status != NC_NOERR) return status; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(NC_CHAR, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = NC_CHAR; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_text(&xp, nelems, value); if(status != NC_NOERR) return status; } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } attrp = new_NC_attr(name, NC_CHAR, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_text(&xp, nelems, value); if(status != NC_NOERR) return status; } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { status = incr_NC_attrarray(ncap, attrp); if(status != NC_NOERR) { free_NC_attr(attrp); return status; } } return NC_NOERR; } int nc_get_att_text(int ncid, int varid, const char *name, char *str) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type != NC_CHAR) return NC_ECHAR; /* else */ { const void *xp = attrp->xvalue; return ncx_pad_getn_text(&xp, attrp->nelems, str); } } int nc_put_att_schar(int ncid, int varid, const char *name, nc_type type, size_t nelems, const signed char *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ischar(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ischar */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ischar(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ischar */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } int nc_get_att_schar(int ncid, int varid, const char *name, signed char *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_Ischar(&xp, attrp->nelems, tp, attrp->type); } } int nc_put_att_uchar(int ncid, int varid, const char *name, nc_type type, size_t nelems, const unsigned char *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Iuchar(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Iuchar */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Iuchar(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Iuchar */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } int nc_get_att_uchar(int ncid, int varid, const char *name, unsigned char *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_Iuchar(&xp, attrp->nelems, tp, attrp->type); } } int nc_put_att_short(int ncid, int varid, const char *name, nc_type type, size_t nelems, const short *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ishort(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ishort */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ishort(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ishort */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } int nc_get_att_short(int ncid, int varid, const char *name, short *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_Ishort(&xp, attrp->nelems, tp, attrp->type); } } int nc_put_att_int(int ncid, int varid, const char *name, nc_type type, size_t nelems, const int *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Iint(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Iint */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Iint(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Iint */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } int nc_get_att_int(int ncid, int varid, const char *name, int *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_Iint(&xp, attrp->nelems, tp, attrp->type); } } int nc_put_att_long(int ncid, int varid, const char *name, nc_type type, size_t nelems, const long *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ilong(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ilong */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ilong(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ilong */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } int nc_get_att_long(int ncid, int varid, const char *name, long *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_Ilong(&xp, attrp->nelems, tp, attrp->type); } } int nc_put_att_float(int ncid, int varid, const char *name, nc_type type, size_t nelems, const float *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ifloat(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ifloat */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Ifloat(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Ifloat */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } int nc_get_att_float(int ncid, int varid, const char *name, float *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_Ifloat(&xp, attrp->nelems, tp, attrp->type); } } int nc_put_att_double(int ncid, int varid, const char *name, nc_type type, size_t nelems, const double *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Idouble(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Idouble */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_Idouble(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_Idouble */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } int nc_get_att_double(int ncid, int varid, const char *name, double *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_Idouble(&xp, attrp->nelems, tp, attrp->type); } } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/CVS/0000755000175000017500000000000011606020250021113 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtknetcdf/CVS/Entries0000644000175000017500000000272511606020250022455 0ustar amckinstryamckinstry/.NoDartCoverage/1.1/Wed Jan 6 16:34:02 2010// /CMakeLists.txt/1.1/Wed Jan 6 16:34:04 2010// /COPYRIGHT/1.1/Wed Jan 6 16:34:05 2010// /README.netcdf/1.1/Wed Jan 6 16:34:05 2010// /README.txt/1.1/Wed Jan 6 16:34:05 2010// /RELEASE_NOTES/1.1/Wed Jan 6 16:34:05 2010// /attr.c/1.1/Wed Jan 6 16:34:05 2010// /attr.m4/1.1/Wed Jan 6 16:34:05 2010// /dim.c/1.1/Wed Jan 6 16:34:05 2010// /error.c/1.1/Wed Jan 6 16:34:05 2010// /fbits.h/1.1/Wed Jan 6 16:34:05 2010// /ffio.c/1.1/Wed Jan 6 16:34:05 2010// /libvers.c/1.1/Wed Jan 6 16:34:05 2010// /nc.c/1.1/Wed Jan 6 16:34:05 2010// /nc.h/1.1/Wed Jan 6 16:34:05 2010// /nc3convert.h/1.1/Wed Jan 6 16:34:05 2010// /ncconfig.h.in/1.1/Wed Jan 6 16:34:05 2010// /ncio.h/1.1/Wed Jan 6 16:34:05 2010// /ncx.c/1.1/Wed Jan 6 16:34:05 2010// /ncx.h/1.1/Wed Jan 6 16:34:05 2010// /ncx.m4/1.1/Wed Jan 6 16:34:05 2010// /netcdf.3/1.1/Wed Jan 6 16:34:07 2010// /netcdf.h/1.1/Wed Jan 6 16:34:07 2010// /netcdf3.h/1.1/Wed Jan 6 16:34:07 2010// /onstack.h/1.1/Wed Jan 6 16:34:07 2010// /posixio.c/1.1/Wed Jan 6 16:34:07 2010// /putget.c/1.1/Wed Jan 6 16:34:07 2010// /putget.m4/1.1/Wed Jan 6 16:34:07 2010// /rnd.h/1.1/Wed Jan 6 16:34:07 2010// /string.c/1.1/Wed Jan 6 16:34:07 2010// /t_nc.c/1.1/Wed Jan 6 16:34:07 2010// /v1hpg.c/1.1/Wed Jan 6 16:34:07 2010// /v2i.c/1.1/Wed Jan 6 16:34:07 2010// /var.c/1.1/Wed Jan 6 16:34:07 2010// /vtk_netcdf.h/1.1/Wed Jan 6 16:34:07 2010// /vtk_netcdf_mangle.h/1.1/Wed Jan 6 16:34:07 2010// D xdmf-2.1.dfsg.1/Utilities/vtknetcdf/CVS/Repository0000644000175000017500000000003111606020250023207 0ustar amckinstryamckinstryXdmf/Utilities/vtknetcdf xdmf-2.1.dfsg.1/Utilities/vtknetcdf/CVS/Root0000644000175000017500000000006411606020250021761 0ustar amckinstryamckinstry:pserver:anonymous@public.kitware.com:/cvsroot/Xdmf xdmf-2.1.dfsg.1/Utilities/vtknetcdf/ncx.c0000644000175000017500000025056311606020250021427 0ustar amckinstryamckinstry/* Do not edit this file. It is produced from the corresponding .m4 source */ /* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. * * This file contains some routines derived from code * which is copyrighted by Sun Microsystems, Inc. * The "#ifdef vax" versions of * ncx_put_float_float() * ncx_get_float_float() * ncx_put_double_double() * ncx_get_double_double() * ncx_putn_float_float() * ncx_getn_float_float() * ncx_putn_double_double() * ncx_getn_double_double() * are derived from xdr_float() and xdr_double() routines * in the freely available, copyrighted Sun RPCSRC 3.9 * distribution, xdr_float.c. * Our "value added" is that these are always memory to memory, * they handle IEEE subnormals properly, and their "n" versions * operate speedily on arrays. */ /* $Id: ncx.c,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ /* * An external data representation interface. */ #include "ncx.h" #include #include /* alias poorly named limits.h macros */ #define SHORT_MAX SHRT_MAX #define SHORT_MIN SHRT_MIN #define USHORT_MAX USHRT_MAX #include #ifndef FLT_MAX /* This POSIX macro missing on some systems */ # ifndef NO_IEEE_FLOAT # define FLT_MAX 3.40282347e+38f # else # error "You will need to define FLT_MAX" # endif #endif #include /* * If the machine's float domain is "smaller" than the external one * use the machine domain */ #if defined(FLT_MAX_EXP) && FLT_MAX_EXP < 128 /* 128 is X_FLT_MAX_EXP */ #undef X_FLOAT_MAX # define X_FLOAT_MAX FLT_MAX #undef X_FLOAT_MIN # define X_FLOAT_MIN (-X_FLOAT_MAX) #endif #if _SX /* NEC SUPER UX */ #if _INT64 #undef INT_MAX /* workaround cpp bug */ #define INT_MAX X_INT_MAX #undef INT_MIN /* workaround cpp bug */ #define INT_MIN X_INT_MIN #undef LONG_MAX /* workaround cpp bug */ #define LONG_MAX X_INT_MAX #undef LONG_MIN /* workaround cpp bug */ #define LONG_MIN X_INT_MIN #elif _LONG64 #undef LONG_MAX /* workaround cpp bug */ #define LONG_MAX 4294967295L #undef LONG_MIN /* workaround cpp bug */ #define LONG_MIN -4294967295L #endif #endif /* _SX */ static const char nada[X_ALIGN] = {0, 0, 0, 0}; #ifndef WORDS_BIGENDIAN /* LITTLE_ENDIAN: DEC and intel */ /* * Routines to convert to BIGENDIAN. * Optimize the swapn?b() and swap?b() routines aggressivly. */ #define SWAP2(a) ( (((a) & 0xff) << 8) | \ (((a) >> 8) & 0xff) ) #define SWAP4(a) ( ((a) << 24) | \ (((a) << 8) & 0x00ff0000) | \ (((a) >> 8) & 0x0000ff00) | \ (((a) >> 24) & 0x000000ff) ) static void swapn2b(void *dst, const void *src, size_t nn) { char *op = dst; const char *ip = src; /* unroll the following to reduce loop overhead * * while(nn-- != 0) * { * *op++ = *(++ip); * *op++ = *(ip++ -1); * } */ while(nn > 3) { *op++ = *(++ip); *op++ = *(ip++ -1); *op++ = *(++ip); *op++ = *(ip++ -1); *op++ = *(++ip); *op++ = *(ip++ -1); *op++ = *(++ip); *op++ = *(ip++ -1); nn -= 4; } while(nn-- != 0) { *op++ = *(++ip); *op++ = *(ip++ -1); } } # ifndef vax static void swap4b(void *dst, const void *src) { char *op = dst; const char *ip = src; op[0] = ip[3]; op[1] = ip[2]; op[2] = ip[1]; op[3] = ip[0]; } # endif /* !vax */ static void swapn4b(void *dst, const void *src, size_t nn) { char *op = dst; const char *ip = src; /* unroll the following to reduce loop overhead * while(nn-- != 0) * { * op[0] = ip[3]; * op[1] = ip[2]; * op[2] = ip[1]; * op[3] = ip[0]; * op += 4; * ip += 4; * } */ while(nn > 3) { op[0] = ip[3]; op[1] = ip[2]; op[2] = ip[1]; op[3] = ip[0]; op[4] = ip[7]; op[5] = ip[6]; op[6] = ip[5]; op[7] = ip[4]; op[8] = ip[11]; op[9] = ip[10]; op[10] = ip[9]; op[11] = ip[8]; op[12] = ip[15]; op[13] = ip[14]; op[14] = ip[13]; op[15] = ip[12]; op += 16; ip += 16; nn -= 4; } while(nn-- != 0) { op[0] = ip[3]; op[1] = ip[2]; op[2] = ip[1]; op[3] = ip[0]; op += 4; ip += 4; } } # ifndef vax static void swap8b(void *dst, const void *src) { char *op = dst; const char *ip = src; op[0] = ip[7]; op[1] = ip[6]; op[2] = ip[5]; op[3] = ip[4]; op[4] = ip[3]; op[5] = ip[2]; op[6] = ip[1]; op[7] = ip[0]; } # endif /* !vax */ # ifndef vax static void swapn8b(void *dst, const void *src, size_t nn) { char *op = dst; const char *ip = src; /* unroll the following to reduce loop overhead * while(nn-- != 0) * { * op[0] = ip[7]; * op[1] = ip[6]; * op[2] = ip[5]; * op[3] = ip[4]; * op[4] = ip[3]; * op[5] = ip[2]; * op[6] = ip[1]; * op[7] = ip[0]; * op += 8; * ip += 8; * } */ while(nn > 1) { op[0] = ip[7]; op[1] = ip[6]; op[2] = ip[5]; op[3] = ip[4]; op[4] = ip[3]; op[5] = ip[2]; op[6] = ip[1]; op[7] = ip[0]; op[8] = ip[15]; op[9] = ip[14]; op[10] = ip[13]; op[11] = ip[12]; op[12] = ip[11]; op[13] = ip[10]; op[14] = ip[9]; op[15] = ip[8]; op += 16; ip += 16; nn -= 2; } while(nn-- != 0) { op[0] = ip[7]; op[1] = ip[6]; op[2] = ip[5]; op[3] = ip[4]; op[4] = ip[3]; op[5] = ip[2]; op[6] = ip[1]; op[7] = ip[0]; op += 8; ip += 8; } } # endif /* !vax */ #endif /* LITTLE_ENDIAN */ /* * Primitive numeric conversion functions. */ /* x_schar */ /* We don't implement and x_schar primitives. */ /* x_short */ #if SHORT_MAX == X_SHORT_MAX typedef short ix_short; #define SIZEOF_IX_SHORT SIZEOF_SHORT #define IX_SHORT_MAX SHORT_MAX #elif INT_MAX >= X_SHORT_MAX typedef int ix_short; #define SIZEOF_IX_SHORT SIZEOF_INT #define IX_SHORT_MAX INT_MAX #elif LONG_MAX >= X_SHORT_MAX typedef long ix_short; #define SIZEOF_IX_SHORT SIZEOF_LONG #define IX_SHORT_MAX LONG_MAX #else #error "ix_short implementation" #endif static void get_ix_short(const void *xp, ix_short *ip) { const uchar *cp = (const uchar *) xp; *ip = *cp++ << 8; #if SIZEOF_IX_SHORT > X_SIZEOF_SHORT if(*ip & 0x8000) { /* extern is negative */ *ip |= (~(0xffff)); /* N.B. Assumes "twos complement" */ } #endif *ip |= *cp; } static void put_ix_short(void *xp, const ix_short *ip) { uchar *cp = (uchar *) xp; *cp++ = (uchar)( (*ip) >> 8 ); *cp = (uchar)(*ip) & 0xff; } int ncx_get_short_schar(const void *xp, schar *ip) { ix_short xx; get_ix_short(xp, &xx); *ip = (schar)xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_short_uchar(const void *xp, uchar *ip) { ix_short xx; get_ix_short(xp, &xx); *ip = (uchar)xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_short_short(const void *xp, short *ip) { #if SIZEOF_IX_SHORT == SIZEOF_SHORT && IX_SHORT_MAX == SHORT_MAX get_ix_short(xp, (ix_short *)ip); return ENOERR; #else ix_short xx; get_ix_short(xp, &xx); *ip = xx; # if IX_SHORT_MAX > SHORT_MAX if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_short_int(const void *xp, int *ip) { #if SIZEOF_IX_SHORT == SIZEOF_INT && IX_SHORT_MAX == INT_MAX get_ix_short(xp, (ix_short *)ip); return ENOERR; #else ix_short xx; get_ix_short(xp, &xx); *ip = xx; # if IX_SHORT_MAX > INT_MAX if(xx > INT_MAX || xx < INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_short_long(const void *xp, long *ip) { #if SIZEOF_IX_SHORT == SIZEOF_LONG && IX_SHORT_MAX == LONG_MAX get_ix_short(xp, (ix_short *)ip); return ENOERR; #else /* assert(LONG_MAX >= X_SHORT_MAX); */ ix_short xx; get_ix_short(xp, &xx); *ip = xx; return ENOERR; #endif } int ncx_get_short_float(const void *xp, float *ip) { ix_short xx; get_ix_short(xp, &xx); *ip = xx; #if 0 /* TODO: determine when necessary */ if(xx > FLT_MAX || xx < (-FLT_MAX)) return NC_ERANGE; #endif return ENOERR; } int ncx_get_short_double(const void *xp, double *ip) { /* assert(DBL_MAX >= X_SHORT_MAX); */ ix_short xx; get_ix_short(xp, &xx); *ip = xx; return ENOERR; } int ncx_put_short_schar(void *xp, const schar *ip) { uchar *cp = (uchar *) xp; if(*ip & 0x80) *cp++ = 0xff; else *cp++ = 0; *cp = (uchar)*ip; return ENOERR; } int ncx_put_short_uchar(void *xp, const uchar *ip) { uchar *cp = (uchar *) xp; *cp++ = 0; *cp = *ip; return ENOERR; } int ncx_put_short_short(void *xp, const short *ip) { #if SIZEOF_IX_SHORT == SIZEOF_SHORT && X_SHORT_MAX == SHORT_MAX put_ix_short(xp, (const ix_short *)ip); return ENOERR; #else ix_short xx = (ix_short)*ip; put_ix_short(xp, &xx); # if X_SHORT_MAX < SHORT_MAX if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_short_int(void *xp, const int *ip) { #if SIZEOF_IX_SHORT == SIZEOF_INT && X_SHORT_MAX == INT_MAX put_ix_short(xp, (const ix_short *)ip); return ENOERR; #else ix_short xx = (ix_short)*ip; put_ix_short(xp, &xx); # if X_SHORT_MAX < INT_MAX if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_short_long(void *xp, const long *ip) { #if SIZEOF_IX_SHORT == SIZEOF_LONG && X_SHORT_MAX == LONG_MAX put_ix_short(xp, (const ix_short *)ip); return ENOERR; #else ix_short xx = (ix_short)*ip; put_ix_short(xp, &xx); # if X_SHORT_MAX < LONG_MAX if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_short_float(void *xp, const float *ip) { ix_short xx = (ix_short) *ip; put_ix_short(xp, &xx); if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; return ENOERR; } int ncx_put_short_double(void *xp, const double *ip) { ix_short xx = (ix_short) *ip; put_ix_short(xp, &xx); if(*ip > X_SHORT_MAX || *ip < X_SHORT_MIN) return NC_ERANGE; return ENOERR; } /* x_int */ #if SHORT_MAX == X_INT_MAX typedef short ix_int; #define SIZEOF_IX_INT SIZEOF_SHORT #define IX_INT_MAX SHORT_MAX #elif INT_MAX >= X_INT_MAX typedef int ix_int; #define SIZEOF_IX_INT SIZEOF_INT #define IX_INT_MAX INT_MAX #elif LONG_MAX >= X_INT_MAX typedef long ix_int; #define SIZEOF_IX_INT SIZEOF_LONG #define IX_INT_MAX LONG_MAX #else #error "ix_int implementation" #endif static void get_ix_int(const void *xp, ix_int *ip) { const uchar *cp = (const uchar *) xp; *ip = *cp++ << 24; #if SIZEOF_IX_INT > X_SIZEOF_INT if(*ip & 0x80000000) { /* extern is negative */ *ip |= (~(0xffffffff)); /* N.B. Assumes "twos complement" */ } #endif *ip |= (*cp++ << 16); *ip |= (*cp++ << 8); *ip |= *cp; } static void put_ix_int(void *xp, const ix_int *ip) { uchar *cp = (uchar *) xp; *cp++ = (uchar)( (*ip) >> 24 ); *cp++ = (uchar)( ((*ip) & 0x00ff0000) >> 16 ); *cp++ = (uchar)( ((*ip) & 0x0000ff00) >> 8 ); *cp = (uchar) ((*ip) & 0x000000ff); } int ncx_get_int_schar(const void *xp, schar *ip) { ix_int xx; get_ix_int(xp, &xx); *ip = (schar)xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_int_uchar(const void *xp, uchar *ip) { ix_int xx; get_ix_int(xp, &xx); *ip = (uchar)xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_int_short(const void *xp, short *ip) { #if SIZEOF_IX_INT == SIZEOF_SHORT && IX_INT_MAX == SHORT_MAX get_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx; get_ix_int(xp, &xx); *ip = (short)xx; # if IX_INT_MAX > SHORT_MAX if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_int_int(const void *xp, int *ip) { #if SIZEOF_IX_INT == SIZEOF_INT && IX_INT_MAX == INT_MAX get_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx; get_ix_int(xp, &xx); *ip = xx; # if IX_INT_MAX > INT_MAX if(xx > INT_MAX || xx < INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_int_long(const void *xp, long *ip) { #if SIZEOF_IX_INT == SIZEOF_LONG && IX_INT_MAX == LONG_MAX get_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx; get_ix_int(xp, &xx); *ip = xx; # if IX_INT_MAX > LONG_MAX /* unlikely */ if(xx > LONG_MAX || xx < LONG_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_get_int_float(const void *xp, float *ip) { ix_int xx; get_ix_int(xp, &xx); *ip = (float)xx; #if 0 /* TODO: determine when necessary */ if(xx > FLT_MAX || xx < (-FLT_MAX)) return NC_ERANGE; #endif return ENOERR; } int ncx_get_int_double(const void *xp, double *ip) { /* assert((DBL_MAX >= X_INT_MAX); */ ix_int xx; get_ix_int(xp, &xx); *ip = xx; return ENOERR; } int ncx_put_int_schar(void *xp, const schar *ip) { uchar *cp = (uchar *) xp; if(*ip & 0x80) { *cp++ = 0xff; *cp++ = 0xff; *cp++ = 0xff; } else { *cp++ = 0x00; *cp++ = 0x00; *cp++ = 0x00; } *cp = (uchar)*ip; return ENOERR; } int ncx_put_int_uchar(void *xp, const uchar *ip) { uchar *cp = (uchar *) xp; *cp++ = 0x00; *cp++ = 0x00; *cp++ = 0x00; *cp = *ip; return ENOERR; } int ncx_put_int_short(void *xp, const short *ip) { #if SIZEOF_IX_INT == SIZEOF_SHORT && IX_INT_MAX == SHORT_MAX put_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); # if IX_INT_MAX < SHORT_MAX if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_int_int(void *xp, const int *ip) { #if SIZEOF_IX_INT == SIZEOF_INT && IX_INT_MAX == INT_MAX put_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); # if IX_INT_MAX < INT_MAX if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_int_long(void *xp, const long *ip) { #if SIZEOF_IX_INT == SIZEOF_LONG && IX_INT_MAX == LONG_MAX put_ix_int(xp, (ix_int *)ip); return ENOERR; #else ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); # if IX_INT_MAX < LONG_MAX if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; # endif return ENOERR; #endif } int ncx_put_int_float(void *xp, const float *ip) { ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); if(*ip > (double)X_INT_MAX || *ip < (double)X_INT_MIN) return NC_ERANGE; return ENOERR; } int ncx_put_int_double(void *xp, const double *ip) { ix_int xx = (ix_int)(*ip); put_ix_int(xp, &xx); if(*ip > X_INT_MAX || *ip < X_INT_MIN) return NC_ERANGE; return ENOERR; } /* x_float */ #if X_SIZEOF_FLOAT == SIZEOF_FLOAT && !defined(NO_IEEE_FLOAT) static void get_ix_float(const void *xp, float *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(ip, xp, sizeof(float)); #else swap4b(ip, xp); #endif } static void put_ix_float(void *xp, const float *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(xp, ip, X_SIZEOF_FLOAT); #else swap4b(xp, ip); #endif } #elif vax /* What IEEE single precision floating point looks like on a Vax */ struct ieee_single { unsigned int exp_hi : 7; unsigned int sign : 1; unsigned int mant_hi : 7; unsigned int exp_lo : 1; unsigned int mant_lo_hi : 8; unsigned int mant_lo_lo : 8; }; /* Vax single precision floating point */ struct vax_single { unsigned int mantissa1 : 7; unsigned int exp : 8; unsigned int sign : 1; unsigned int mantissa2 : 16; }; #define VAX_SNG_BIAS 0x81 #define IEEE_SNG_BIAS 0x7f static struct sgl_limits { struct vax_single s; struct ieee_single ieee; } max = { { 0x7f, 0xff, 0x0, 0xffff }, /* Max Vax */ { 0x7f, 0x0, 0x0, 0x1, 0x0, 0x0 } /* Max IEEE */ }; static struct sgl_limits min = { { 0x0, 0x0, 0x0, 0x0 }, /* Min Vax */ { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } /* Min IEEE */ }; static void get_ix_float(const void *xp, float *ip) { struct vax_single *const vsp = (struct vax_single *) ip; const struct ieee_single *const isp = (const struct ieee_single *) xp; unsigned exp = isp->exp_hi << 1 | isp->exp_lo; switch(exp) { case 0 : /* ieee subnormal */ if(isp->mant_hi == min.ieee.mant_hi && isp->mant_lo_hi == min.ieee.mant_lo_hi && isp->mant_lo_lo == min.ieee.mant_lo_lo) { *vsp = min.s; } else { unsigned mantissa = (isp->mant_hi << 16) | isp->mant_lo_hi << 8 | isp->mant_lo_lo; unsigned tmp = mantissa >> 20; if(tmp >= 4) { vsp->exp = 2; } else if (tmp >= 2) { vsp->exp = 1; } else { *vsp = min.s; break; } /* else */ tmp = mantissa - (1 << (20 + vsp->exp )); tmp <<= 3 - vsp->exp; vsp->mantissa2 = tmp; vsp->mantissa1 = (tmp >> 16); } break; case 0xfe : case 0xff : *vsp = max.s; break; default : vsp->exp = exp - IEEE_SNG_BIAS + VAX_SNG_BIAS; vsp->mantissa2 = isp->mant_lo_hi << 8 | isp->mant_lo_lo; vsp->mantissa1 = isp->mant_hi; } vsp->sign = isp->sign; } static void put_ix_float(void *xp, const float *ip) { const struct vax_single *const vsp = (const struct vax_single *)ip; struct ieee_single *const isp = (struct ieee_single *) xp; switch(vsp->exp){ case 0 : /* all vax float with zero exponent map to zero */ *isp = min.ieee; break; case 2 : case 1 : { /* These will map to subnormals */ unsigned mantissa = (vsp->mantissa1 << 16) | vsp->mantissa2; mantissa >>= 3 - vsp->exp; mantissa += (1 << (20 + vsp->exp)); isp->mant_lo_lo = mantissa; isp->mant_lo_hi = mantissa >> 8; isp->mant_hi = mantissa >> 16; isp->exp_lo = 0; isp->exp_hi = 0; } break; case 0xff : /* max.s.exp */ if( vsp->mantissa2 == max.s.mantissa2 && vsp->mantissa1 == max.s.mantissa1) { /* map largest vax float to ieee infinity */ *isp = max.ieee; break; } /* else, fall thru */ default : { unsigned exp = vsp->exp - VAX_SNG_BIAS + IEEE_SNG_BIAS; isp->exp_hi = exp >> 1; isp->exp_lo = exp; isp->mant_lo_lo = vsp->mantissa2; isp->mant_lo_hi = vsp->mantissa2 >> 8; isp->mant_hi = vsp->mantissa1; } } isp->sign = vsp->sign; } /* vax */ #elif defined(_CRAY) && !defined(__crayx1) /* * Return the number of bytes until the next "word" boundary * N.B. This is based on the very wierd YMP address structure, * which puts the address within a word in the leftmost 3 bits * of the address. */ static size_t word_align(const void *vp) { const size_t rem = ((size_t)vp >> (64 - 3)) & 0x7; return (rem != 0); } struct ieee_single_hi { unsigned int sign : 1; unsigned int exp : 8; unsigned int mant :23; unsigned int pad :32; }; typedef struct ieee_single_hi ieee_single_hi; struct ieee_single_lo { unsigned int pad :32; unsigned int sign : 1; unsigned int exp : 8; unsigned int mant :23; }; typedef struct ieee_single_lo ieee_single_lo; static const int ieee_single_bias = 0x7f; struct ieee_double { unsigned int sign : 1; unsigned int exp :11; unsigned int mant :52; }; typedef struct ieee_double ieee_double; static const int ieee_double_bias = 0x3ff; #if defined(NO_IEEE_FLOAT) struct cray_single { unsigned int sign : 1; unsigned int exp :15; unsigned int mant :48; }; typedef struct cray_single cray_single; static const int cs_ieis_bias = 0x4000 - 0x7f; static const int cs_id_bias = 0x4000 - 0x3ff; static void get_ix_float(const void *xp, float *ip) { if(word_align(xp) == 0) { const ieee_single_hi *isp = (const ieee_single_hi *) xp; cray_single *csp = (cray_single *) ip; if(isp->exp == 0) { /* ieee subnormal */ *ip = (double)isp->mant; if(isp->mant != 0) { csp->exp -= (ieee_single_bias + 22); } } else { csp->exp = isp->exp + cs_ieis_bias + 1; csp->mant = isp->mant << (48 - 1 - 23); csp->mant |= (1 << (48 - 1)); } csp->sign = isp->sign; } else { const ieee_single_lo *isp = (const ieee_single_lo *) xp; cray_single *csp = (cray_single *) ip; if(isp->exp == 0) { /* ieee subnormal */ *ip = (double)isp->mant; if(isp->mant != 0) { csp->exp -= (ieee_single_bias + 22); } } else { csp->exp = isp->exp + cs_ieis_bias + 1; csp->mant = isp->mant << (48 - 1 - 23); csp->mant |= (1 << (48 - 1)); } csp->sign = isp->sign; } } static void put_ix_float(void *xp, const float *ip) { if(word_align(xp) == 0) { ieee_single_hi *isp = (ieee_single_hi*)xp; const cray_single *csp = (const cray_single *) ip; int ieee_exp = csp->exp - cs_ieis_bias -1; isp->sign = csp->sign; if(ieee_exp >= 0xff) { /* NC_ERANGE => ieee Inf */ isp->exp = 0xff; isp->mant = 0x0; } else if(ieee_exp > 0) { /* normal ieee representation */ isp->exp = ieee_exp; /* assumes cray rep is in normal form */ assert(csp->mant & 0x800000000000); isp->mant = (((csp->mant << 1) & 0xffffffffffff) >> (48 - 23)); } else if(ieee_exp > -23) { /* ieee subnormal, right shift */ const int rshift = (48 - 23 - ieee_exp); isp->mant = csp->mant >> rshift; #if 0 if(csp->mant & (1 << (rshift -1))) { /* round up */ isp->mant++; } #endif isp->exp = 0; } else { /* smaller than ieee can represent */ isp->exp = 0; isp->mant = 0; } } else { ieee_single_lo *isp = (ieee_single_lo*)xp; const cray_single *csp = (const cray_single *) ip; int ieee_exp = csp->exp - cs_ieis_bias -1; isp->sign = csp->sign; if(ieee_exp >= 0xff) { /* NC_ERANGE => ieee Inf */ isp->exp = 0xff; isp->mant = 0x0; } else if(ieee_exp > 0) { /* normal ieee representation */ isp->exp = ieee_exp; /* assumes cray rep is in normal form */ assert(csp->mant & 0x800000000000); isp->mant = (((csp->mant << 1) & 0xffffffffffff) >> (48 - 23)); } else if(ieee_exp > -23) { /* ieee subnormal, right shift */ const int rshift = (48 - 23 - ieee_exp); isp->mant = csp->mant >> rshift; #if 0 if(csp->mant & (1 << (rshift -1))) { /* round up */ isp->mant++; } #endif isp->exp = 0; } else { /* smaller than ieee can represent */ isp->exp = 0; isp->mant = 0; } } } #else /* IEEE Cray with only doubles */ static void get_ix_float(const void *xp, float *ip) { ieee_double *idp = (ieee_double *) ip; if(word_align(xp) == 0) { const ieee_single_hi *isp = (const ieee_single_hi *) xp; if(isp->exp == 0 && isp->mant == 0) { idp->exp = 0; idp->mant = 0; } else { idp->exp = isp->exp + (ieee_double_bias - ieee_single_bias); idp->mant = isp->mant << (52 - 23); } idp->sign = isp->sign; } else { const ieee_single_lo *isp = (const ieee_single_lo *) xp; if(isp->exp == 0 && isp->mant == 0) { idp->exp = 0; idp->mant = 0; } else { idp->exp = isp->exp + (ieee_double_bias - ieee_single_bias); idp->mant = isp->mant << (52 - 23); } idp->sign = isp->sign; } } static void put_ix_float(void *xp, const float *ip) { const ieee_double *idp = (const ieee_double *) ip; if(word_align(xp) == 0) { ieee_single_hi *isp = (ieee_single_hi*)xp; if(idp->exp > (ieee_double_bias - ieee_single_bias)) isp->exp = idp->exp - (ieee_double_bias - ieee_single_bias); else isp->exp = 0; isp->mant = idp->mant >> (52 - 23); isp->sign = idp->sign; } else { ieee_single_lo *isp = (ieee_single_lo*)xp; if(idp->exp > (ieee_double_bias - ieee_single_bias)) isp->exp = idp->exp - (ieee_double_bias - ieee_single_bias); else isp->exp = 0; isp->mant = idp->mant >> (52 - 23); isp->sign = idp->sign; } } #endif #elif _SX && _FLOAT2 static void get_ix_float(const void *xp, float *ip) { const int ncnv = ie3_fl2(xp, ip, 4, 8, 1); } static void put_ix_float(void *xp, const float *ip) { const int ncnv = fl2_ie3(ip, xp, 8, 4, 1); } #else #error "ix_float implementation" #endif int ncx_get_float_schar(const void *xp, schar *ip) { float xx; get_ix_float(xp, &xx); *ip = (schar) xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_uchar(const void *xp, uchar *ip) { float xx; get_ix_float(xp, &xx); *ip = (uchar) xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_float_short(const void *xp, short *ip) { float xx; get_ix_float(xp, &xx); *ip = (short) xx; if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_int(const void *xp, int *ip) { float xx; get_ix_float(xp, &xx); *ip = (int) xx; if(xx > (double)INT_MAX || xx < (double)INT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_long(const void *xp, long *ip) { float xx; get_ix_float(xp, &xx); *ip = (long) xx; if(xx > LONG_MAX || xx < LONG_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_float_float(const void *xp, float *ip) { /* TODO */ get_ix_float(xp, ip); return ENOERR; } int ncx_get_float_double(const void *xp, double *ip) { /* TODO */ float xx; get_ix_float(xp, &xx); *ip = xx; return ENOERR; } int ncx_put_float_schar(void *xp, const schar *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); return ENOERR; } int ncx_put_float_uchar(void *xp, const uchar *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); return ENOERR; } int ncx_put_float_short(void *xp, const short *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); #if 0 /* TODO: figure this out */ if((float)(*ip) > X_FLOAT_MAX || (float)(*ip) < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_int(void *xp, const int *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); #if 1 /* TODO: figure this out */ if((float)(*ip) > X_FLOAT_MAX || (float)(*ip) < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_long(void *xp, const long *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); #if 1 /* TODO: figure this out */ if((float)(*ip) > X_FLOAT_MAX || (float)(*ip) < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_float(void *xp, const float *ip) { put_ix_float(xp, ip); #ifdef NO_IEEE_FLOAT if(*ip > X_FLOAT_MAX || *ip < X_FLOAT_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_float_double(void *xp, const double *ip) { float xx = (float) *ip; put_ix_float(xp, &xx); if(*ip > X_FLOAT_MAX || *ip < X_FLOAT_MIN) return NC_ERANGE; return ENOERR; } /* x_double */ #if X_SIZEOF_DOUBLE == SIZEOF_DOUBLE && !defined(NO_IEEE_FLOAT) static void get_ix_double(const void *xp, double *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(ip, xp, sizeof(double)); #else swap8b(ip, xp); #endif } static void put_ix_double(void *xp, const double *ip) { #ifdef WORDS_BIGENDIAN (void) memcpy(xp, ip, X_SIZEOF_DOUBLE); #else swap8b(xp, ip); #endif } #elif vax /* What IEEE double precision floating point looks like on a Vax */ struct ieee_double { unsigned int exp_hi : 7; unsigned int sign : 1; unsigned int mant_6 : 4; unsigned int exp_lo : 4; unsigned int mant_5 : 8; unsigned int mant_4 : 8; unsigned int mant_lo : 32; }; /* Vax double precision floating point */ struct vax_double { unsigned int mantissa1 : 7; unsigned int exp : 8; unsigned int sign : 1; unsigned int mantissa2 : 16; unsigned int mantissa3 : 16; unsigned int mantissa4 : 16; }; #define VAX_DBL_BIAS 0x81 #define IEEE_DBL_BIAS 0x3ff #define MASK(nbits) ((1 << nbits) - 1) static const struct dbl_limits { struct vax_double d; struct ieee_double ieee; } dbl_limits[2] = { {{ 0x7f, 0xff, 0x0, 0xffff, 0xffff, 0xffff }, /* Max Vax */ { 0x7f, 0x0, 0x0, 0xf, 0x0, 0x0, 0x0}}, /* Max IEEE */ {{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, /* Min Vax */ { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}}, /* Min IEEE */ }; static void get_ix_double(const void *xp, double *ip) { struct vax_double *const vdp = (struct vax_double *)ip; const struct ieee_double *const idp = (const struct ieee_double *) xp; { const struct dbl_limits *lim; int ii; for (ii = 0, lim = dbl_limits; ii < sizeof(dbl_limits)/sizeof(struct dbl_limits); ii++, lim++) { if ((idp->mant_lo == lim->ieee.mant_lo) && (idp->mant_4 == lim->ieee.mant_4) && (idp->mant_5 == lim->ieee.mant_5) && (idp->mant_6 == lim->ieee.mant_6) && (idp->exp_lo == lim->ieee.exp_lo) && (idp->exp_hi == lim->ieee.exp_hi) ) { *vdp = lim->d; goto doneit; } } } { unsigned exp = idp->exp_hi << 4 | idp->exp_lo; vdp->exp = exp - IEEE_DBL_BIAS + VAX_DBL_BIAS; } { unsigned mant_hi = ((idp->mant_6 << 16) | (idp->mant_5 << 8) | idp->mant_4); unsigned mant_lo = SWAP4(idp->mant_lo); vdp->mantissa1 = (mant_hi >> 13); vdp->mantissa2 = ((mant_hi & MASK(13)) << 3) | (mant_lo >> 29); vdp->mantissa3 = (mant_lo >> 13); vdp->mantissa4 = (mant_lo << 3); } doneit: vdp->sign = idp->sign; } static void put_ix_double(void *xp, const double *ip) { const struct vax_double *const vdp = (const struct vax_double *)ip; struct ieee_double *const idp = (struct ieee_double *) xp; if ((vdp->mantissa4 > (dbl_limits[0].d.mantissa4 - 3)) && (vdp->mantissa3 == dbl_limits[0].d.mantissa3) && (vdp->mantissa2 == dbl_limits[0].d.mantissa2) && (vdp->mantissa1 == dbl_limits[0].d.mantissa1) && (vdp->exp == dbl_limits[0].d.exp)) { *idp = dbl_limits[0].ieee; goto shipit; } if ((vdp->mantissa4 == dbl_limits[1].d.mantissa4) && (vdp->mantissa3 == dbl_limits[1].d.mantissa3) && (vdp->mantissa2 == dbl_limits[1].d.mantissa2) && (vdp->mantissa1 == dbl_limits[1].d.mantissa1) && (vdp->exp == dbl_limits[1].d.exp)) { *idp = dbl_limits[1].ieee; goto shipit; } { unsigned exp = vdp->exp - VAX_DBL_BIAS + IEEE_DBL_BIAS; unsigned mant_lo = ((vdp->mantissa2 & MASK(3)) << 29) | (vdp->mantissa3 << 13) | ((vdp->mantissa4 >> 3) & MASK(13)); unsigned mant_hi = (vdp->mantissa1 << 13) | (vdp->mantissa2 >> 3); if((vdp->mantissa4 & 7) > 4) { /* round up */ mant_lo++; if(mant_lo == 0) { mant_hi++; if(mant_hi > 0xffffff) { mant_hi = 0; exp++; } } } idp->mant_lo = SWAP4(mant_lo); idp->mant_6 = mant_hi >> 16; idp->mant_5 = (mant_hi & 0xff00) >> 8; idp->mant_4 = mant_hi; idp->exp_hi = exp >> 4; idp->exp_lo = exp; } shipit: idp->sign = vdp->sign; } /* vax */ #elif defined(_CRAY) && !defined(__crayx1) static void get_ix_double(const void *xp, double *ip) { const ieee_double *idp = (const ieee_double *) xp; cray_single *csp = (cray_single *) ip; if(idp->exp == 0) { /* ieee subnormal */ *ip = (double)idp->mant; if(idp->mant != 0) { csp->exp -= (ieee_double_bias + 51); } } else { csp->exp = idp->exp + cs_id_bias + 1; csp->mant = idp->mant >> (52 - 48 + 1); csp->mant |= (1 << (48 - 1)); } csp->sign = idp->sign; } static void put_ix_double(void *xp, const double *ip) { ieee_double *idp = (ieee_double *) xp; const cray_single *csp = (const cray_single *) ip; int ieee_exp = csp->exp - cs_id_bias -1; idp->sign = csp->sign; if(ieee_exp >= 0x7ff) { /* NC_ERANGE => ieee Inf */ idp->exp = 0x7ff; idp->mant = 0x0; } else if(ieee_exp > 0) { /* normal ieee representation */ idp->exp = ieee_exp; /* assumes cray rep is in normal form */ assert(csp->mant & 0x800000000000); idp->mant = (((csp->mant << 1) & 0xffffffffffff) << (52 - 48)); } else if(ieee_exp >= (-(52 -48))) { /* ieee subnormal, left shift */ const int lshift = (52 - 48) + ieee_exp; idp->mant = csp->mant << lshift; idp->exp = 0; } else if(ieee_exp >= -52) { /* ieee subnormal, right shift */ const int rshift = (- (52 - 48) - ieee_exp); idp->mant = csp->mant >> rshift; #if 0 if(csp->mant & (1 << (rshift -1))) { /* round up */ idp->mant++; } #endif idp->exp = 0; } else { /* smaller than ieee can represent */ idp->exp = 0; idp->mant = 0; } } #elif _SX && _FLOAT2 static void get_ix_double(const void *xp, double *ip) { const int ncnv = ie3_fl2(xp, ip, 8, 8, 1); } static void put_ix_double(void *xp, const double *ip) { const int ncnv = fl2_ie3(ip, xp, 8, 8, 1); } #else #error "ix_double implementation" #endif int ncx_get_double_schar(const void *xp, schar *ip) { double xx; get_ix_double(xp, &xx); *ip = (schar) xx; if(xx > SCHAR_MAX || xx < SCHAR_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_uchar(const void *xp, uchar *ip) { double xx; get_ix_double(xp, &xx); *ip = (uchar) xx; if(xx > UCHAR_MAX || xx < 0) return NC_ERANGE; return ENOERR; } int ncx_get_double_short(const void *xp, short *ip) { double xx; get_ix_double(xp, &xx); *ip = (short) xx; if(xx > SHORT_MAX || xx < SHORT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_int(const void *xp, int *ip) { double xx; get_ix_double(xp, &xx); *ip = (int) xx; if(xx > INT_MAX || xx < INT_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_long(const void *xp, long *ip) { double xx; get_ix_double(xp, &xx); *ip = (long) xx; if(xx > LONG_MAX || xx < LONG_MIN) return NC_ERANGE; return ENOERR; } int ncx_get_double_float(const void *xp, float *ip) { double xx; get_ix_double(xp, &xx); if(xx > FLT_MAX || xx < (-FLT_MAX)) { *ip = FLT_MAX; return NC_ERANGE; } if(xx < (-FLT_MAX)) { *ip = (-FLT_MAX); return NC_ERANGE; } *ip = (float) xx; return ENOERR; } int ncx_get_double_double(const void *xp, double *ip) { /* TODO */ get_ix_double(xp, ip); return ENOERR; } int ncx_put_double_schar(void *xp, const schar *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); return ENOERR; } int ncx_put_double_uchar(void *xp, const uchar *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); return ENOERR; } int ncx_put_double_short(void *xp, const short *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 0 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_int(void *xp, const int *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 0 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_long(void *xp, const long *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 1 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_float(void *xp, const float *ip) { double xx = (double) *ip; put_ix_double(xp, &xx); #if 1 /* TODO: figure this out */ if((double)(*ip) > X_DOUBLE_MAX || (double)(*ip) < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } int ncx_put_double_double(void *xp, const double *ip) { put_ix_double(xp, ip); #ifdef NO_IEEE_FLOAT if(*ip > X_DOUBLE_MAX || *ip < X_DOUBLE_MIN) return NC_ERANGE; #endif return ENOERR; } /* x_size_t */ #if SIZEOF_SIZE_T < X_SIZEOF_SIZE_T #error "x_size_t implementation" /* netcdf requires size_t which can hold values from 0 to 2^32 -1 */ #endif int ncx_put_size_t(void **xpp, const size_t *ulp) { /* similar to put_ix_int() */ uchar *cp = (uchar *) *xpp; #if SIZEOF_SIZE_T != X_SIZEOF_INT assert(*ulp <= X_SIZE_MAX); #endif *cp++ = (uchar)((*ulp) >> 24); *cp++ = (uchar)(((*ulp) & 0x00ff0000) >> 16); *cp++ = (uchar)(((*ulp) & 0x0000ff00) >> 8); *cp = (uchar)((*ulp) & 0x000000ff); *xpp = (void *)((char *)(*xpp) + X_SIZEOF_SIZE_T); return ENOERR; } int ncx_get_size_t(const void **xpp, size_t *ulp) { /* similar to get_ix_int */ const uchar *cp = (const uchar *) *xpp; *ulp = (unsigned)(*cp++ << 24); *ulp |= (*cp++ << 16); *ulp |= (*cp++ << 8); *ulp |= *cp; *xpp = (const void *)((const char *)(*xpp) + X_SIZEOF_SIZE_T); return ENOERR; } /* x_off_t */ int ncx_put_off_t(void **xpp, const off_t *lp, size_t sizeof_off_t) { /* similar to put_ix_int() */ uchar *cp = (uchar *) *xpp; /* No negative offsets stored in netcdf */ if (*lp < 0) { /* Assume this is an overflow of a 32-bit int... */ return ERANGE; } assert(sizeof_off_t == 4 || sizeof_off_t == 8); if (sizeof_off_t == 4) { *cp++ = (uchar) ((*lp) >> 24); *cp++ = (uchar)(((*lp) & 0x00ff0000) >> 16); *cp++ = (uchar)(((*lp) & 0x0000ff00) >> 8); *cp = (uchar)( (*lp) & 0x000000ff); } else { #if SIZEOF_OFF_T == 4 /* Write a 64-bit offset on a system with only a 32-bit offset */ *cp++ = (uchar)0; *cp++ = (uchar)0; *cp++ = (uchar)0; *cp++ = (uchar)0; *cp++ = (uchar)(((*lp) & 0xff000000) >> 24); *cp++ = (uchar)(((*lp) & 0x00ff0000) >> 16); *cp++ = (uchar)(((*lp) & 0x0000ff00) >> 8); *cp = (uchar)( (*lp) & 0x000000ff); #else *cp++ = (uchar) ((*lp) >> 56); *cp++ = (uchar)(((*lp) & 0x00ff000000000000ULL) >> 48); *cp++ = (uchar)(((*lp) & 0x0000ff0000000000ULL) >> 40); *cp++ = (uchar)(((*lp) & 0x000000ff00000000ULL) >> 32); *cp++ = (uchar)(((*lp) & 0x00000000ff000000ULL) >> 24); *cp++ = (uchar)(((*lp) & 0x0000000000ff0000ULL) >> 16); *cp++ = (uchar)(((*lp) & 0x000000000000ff00ULL) >> 8); *cp = (uchar)( (*lp) & 0x00000000000000ffULL); #endif } *xpp = (void *)((char *)(*xpp) + sizeof_off_t); return ENOERR; } int ncx_get_off_t(const void **xpp, off_t *lp, size_t sizeof_off_t) { /* similar to get_ix_int() */ const uchar *cp = (const uchar *) *xpp; assert(sizeof_off_t == 4 || sizeof_off_t == 8); if (sizeof_off_t == 4) { *lp = *cp++ << 24; *lp |= (*cp++ << 16); *lp |= (*cp++ << 8); *lp |= *cp; } else { #if SIZEOF_OFF_T == 4 /* Read a 64-bit offset on a system with only a 32-bit offset */ /* If the offset overflows, set an error code and return */ *lp = ((off_t)(*cp++) << 24); *lp |= ((off_t)(*cp++) << 16); *lp |= ((off_t)(*cp++) << 8); *lp |= ((off_t)(*cp++)); /* * lp now contains the upper 32-bits of the 64-bit offset. if lp is * not zero, then the dataset is larger than can be represented * on this system. Set an error code and return. */ if (*lp != 0) { return ERANGE; } *lp = ((off_t)(*cp++) << 24); *lp |= ((off_t)(*cp++) << 16); *lp |= ((off_t)(*cp++) << 8); *lp |= (off_t)*cp; if (*lp < 0) { /* * If this fails, then the offset is >2^31, but less * than 2^32 which is not allowed, but is not caught * by the previous check */ return ERANGE; } #else *lp = ((off_t)(*cp++) << 56); *lp |= ((off_t)(*cp++) << 48); *lp |= ((off_t)(*cp++) << 40); *lp |= ((off_t)(*cp++) << 32); *lp |= ((off_t)(*cp++) << 24); *lp |= ((off_t)(*cp++) << 16); *lp |= ((off_t)(*cp++) << 8); *lp |= (off_t)*cp; #endif } *xpp = (const void *)((const char *)(*xpp) + sizeof_off_t); return ENOERR; } /* * Aggregate numeric conversion functions. */ /* schar */ int ncx_getn_schar_schar(const void **xpp, size_t nelems, schar *tp) { (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_getn_schar_uchar(const void **xpp, size_t nelems, uchar *tp) { (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_getn_schar_short(const void **xpp, size_t nelems, short *tp) { schar *xp = (schar *)(*xpp); while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (const void *)xp; return ENOERR; } int ncx_getn_schar_int(const void **xpp, size_t nelems, int *tp) { schar *xp = (schar *)(*xpp); while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (const void *)xp; return ENOERR; } int ncx_getn_schar_long(const void **xpp, size_t nelems, long *tp) { schar *xp = (schar *)(*xpp); while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (const void *)xp; return ENOERR; } int ncx_getn_schar_float(const void **xpp, size_t nelems, float *tp) { schar *xp = (schar *)(*xpp); while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (const void *)xp; return ENOERR; } int ncx_getn_schar_double(const void **xpp, size_t nelems, double *tp) { schar *xp = (schar *)(*xpp); while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (const void *)xp; return ENOERR; } int ncx_pad_getn_schar_schar(const void **xpp, size_t nelems, schar *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems + rndup); return ENOERR; } int ncx_pad_getn_schar_uchar(const void **xpp, size_t nelems, uchar *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems + rndup); return ENOERR; } int ncx_pad_getn_schar_short(const void **xpp, size_t nelems, short *tp) { size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (void *)(xp + rndup); return ENOERR; } int ncx_pad_getn_schar_int(const void **xpp, size_t nelems, int *tp) { size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (void *)(xp + rndup); return ENOERR; } int ncx_pad_getn_schar_long(const void **xpp, size_t nelems, long *tp) { size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (void *)(xp + rndup); return ENOERR; } int ncx_pad_getn_schar_float(const void **xpp, size_t nelems, float *tp) { size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (void *)(xp + rndup); return ENOERR; } int ncx_pad_getn_schar_double(const void **xpp, size_t nelems, double *tp) { size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { *tp++ = *xp++; } *xpp = (void *)(xp + rndup); return ENOERR; } int ncx_putn_schar_schar(void **xpp, size_t nelems, const schar *tp) { (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_putn_schar_uchar(void **xpp, size_t nelems, const uchar *tp) { (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_putn_schar_short(void **xpp, size_t nelems, const short *tp) { int status = ENOERR; schar *xp = (schar *) *xpp; while(nelems-- != 0) { if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } *xpp = (void *)xp; return status; } int ncx_putn_schar_int(void **xpp, size_t nelems, const int *tp) { int status = ENOERR; schar *xp = (schar *) *xpp; while(nelems-- != 0) { if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } *xpp = (void *)xp; return status; } int ncx_putn_schar_long(void **xpp, size_t nelems, const long *tp) { int status = ENOERR; schar *xp = (schar *) *xpp; while(nelems-- != 0) { if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } *xpp = (void *)xp; return status; } int ncx_putn_schar_float(void **xpp, size_t nelems, const float *tp) { int status = ENOERR; schar *xp = (schar *) *xpp; while(nelems-- != 0) { if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } *xpp = (void *)xp; return status; } int ncx_putn_schar_double(void **xpp, size_t nelems, const double *tp) { int status = ENOERR; schar *xp = (schar *) *xpp; while(nelems-- != 0) { if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } *xpp = (void *)xp; return status; } int ncx_pad_putn_schar_schar(void **xpp, size_t nelems, const schar *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); if(rndup) { (void) memcpy(*xpp, nada, rndup); *xpp = (void *)((char *)(*xpp) + rndup); } return ENOERR; } int ncx_pad_putn_schar_uchar(void **xpp, size_t nelems, const uchar *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); if(rndup) { (void) memcpy(*xpp, nada, rndup); *xpp = (void *)((char *)(*xpp) + rndup); } return ENOERR; } int ncx_pad_putn_schar_short(void **xpp, size_t nelems, const short *tp) { int status = ENOERR; size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { /* N.B. schar as signed */ if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } if(rndup) { (void) memcpy(xp, nada, rndup); xp += rndup; } *xpp = (void *)xp; return status; } int ncx_pad_putn_schar_int(void **xpp, size_t nelems, const int *tp) { int status = ENOERR; size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { /* N.B. schar as signed */ if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } if(rndup) { (void) memcpy(xp, nada, rndup); xp += rndup; } *xpp = (void *)xp; return status; } int ncx_pad_putn_schar_long(void **xpp, size_t nelems, const long *tp) { int status = ENOERR; size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { /* N.B. schar as signed */ if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } if(rndup) { (void) memcpy(xp, nada, rndup); xp += rndup; } *xpp = (void *)xp; return status; } int ncx_pad_putn_schar_float(void **xpp, size_t nelems, const float *tp) { int status = ENOERR; size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { /* N.B. schar as signed */ if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } if(rndup) { (void) memcpy(xp, nada, rndup); xp += rndup; } *xpp = (void *)xp; return status; } int ncx_pad_putn_schar_double(void **xpp, size_t nelems, const double *tp) { int status = ENOERR; size_t rndup = nelems % X_ALIGN; schar *xp = (schar *) *xpp; if(rndup) rndup = X_ALIGN - rndup; while(nelems-- != 0) { /* N.B. schar as signed */ if(*tp > X_SCHAR_MAX || *tp < X_SCHAR_MIN) status = NC_ERANGE; *xp++ = (schar) *tp++; } if(rndup) { (void) memcpy(xp, nada, rndup); xp += rndup; } *xpp = (void *)xp; return status; } /* short */ int ncx_getn_short_schar(const void **xpp, size_t nelems, schar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_short_uchar(const void **xpp, size_t nelems, uchar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #if X_SIZEOF_SHORT == SIZEOF_SHORT /* optimized version */ int ncx_getn_short_short(const void **xpp, size_t nelems, short *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(short)); # else swapn2b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_SHORT); return ENOERR; } #else int ncx_getn_short_short(const void **xpp, size_t nelems, short *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #endif int ncx_getn_short_int(const void **xpp, size_t nelems, int *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_short_long(const void **xpp, size_t nelems, long *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_short_float(const void **xpp, size_t nelems, float *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_short_double(const void **xpp, size_t nelems, double *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_pad_getn_short_schar(const void **xpp, size_t nelems, schar *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } int ncx_pad_getn_short_uchar(const void **xpp, size_t nelems, uchar *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } int ncx_pad_getn_short_short(const void **xpp, size_t nelems, short *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } int ncx_pad_getn_short_int(const void **xpp, size_t nelems, int *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } int ncx_pad_getn_short_long(const void **xpp, size_t nelems, long *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } int ncx_pad_getn_short_float(const void **xpp, size_t nelems, float *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } int ncx_pad_getn_short_double(const void **xpp, size_t nelems, double *tp) { const size_t rndup = nelems % 2; const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { const int lstatus = ncx_get_short_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) xp += X_SIZEOF_SHORT; *xpp = (void *)xp; return status; } int ncx_putn_short_schar(void **xpp, size_t nelems, const schar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_short_uchar(void **xpp, size_t nelems, const uchar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #if X_SIZEOF_SHORT == SIZEOF_SHORT /* optimized version */ int ncx_putn_short_short(void **xpp, size_t nelems, const short *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_SHORT); # else swapn2b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_SHORT); return ENOERR; } #else int ncx_putn_short_short(void **xpp, size_t nelems, const short *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #endif int ncx_putn_short_int(void **xpp, size_t nelems, const int *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_short_long(void **xpp, size_t nelems, const long *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_short_float(void **xpp, size_t nelems, const float *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_short_double(void **xpp, size_t nelems, const double *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_pad_putn_short_schar(void **xpp, size_t nelems, const schar *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } int ncx_pad_putn_short_uchar(void **xpp, size_t nelems, const uchar *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } int ncx_pad_putn_short_short(void **xpp, size_t nelems, const short *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } int ncx_pad_putn_short_int(void **xpp, size_t nelems, const int *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } int ncx_pad_putn_short_long(void **xpp, size_t nelems, const long *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } int ncx_pad_putn_short_float(void **xpp, size_t nelems, const float *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } int ncx_pad_putn_short_double(void **xpp, size_t nelems, const double *tp) { const size_t rndup = nelems % 2; char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_SHORT, tp++) { int lstatus = ncx_put_short_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } if(rndup != 0) { (void) memcpy(xp, nada, X_SIZEOF_SHORT); xp += X_SIZEOF_SHORT; } *xpp = (void *)xp; return status; } /* int */ int ncx_getn_int_schar(const void **xpp, size_t nelems, schar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { const int lstatus = ncx_get_int_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_int_uchar(const void **xpp, size_t nelems, uchar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { const int lstatus = ncx_get_int_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_int_short(const void **xpp, size_t nelems, short *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { const int lstatus = ncx_get_int_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #if X_SIZEOF_INT == SIZEOF_INT /* optimized version */ int ncx_getn_int_int(const void **xpp, size_t nelems, int *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(int)); # else swapn4b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else int ncx_getn_int_int(const void **xpp, size_t nelems, int *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { const int lstatus = ncx_get_int_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #endif #if X_SIZEOF_INT == SIZEOF_LONG /* optimized version */ int ncx_getn_int_long(const void **xpp, size_t nelems, long *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(long)); # else swapn4b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else int ncx_getn_int_long(const void **xpp, size_t nelems, long *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { const int lstatus = ncx_get_int_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #endif int ncx_getn_int_float(const void **xpp, size_t nelems, float *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { const int lstatus = ncx_get_int_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_int_double(const void **xpp, size_t nelems, double *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { const int lstatus = ncx_get_int_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_putn_int_schar(void **xpp, size_t nelems, const schar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { int lstatus = ncx_put_int_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_int_uchar(void **xpp, size_t nelems, const uchar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { int lstatus = ncx_put_int_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_int_short(void **xpp, size_t nelems, const short *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { int lstatus = ncx_put_int_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #if X_SIZEOF_INT == SIZEOF_INT /* optimized version */ int ncx_putn_int_int(void **xpp, size_t nelems, const int *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_INT); # else swapn4b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else int ncx_putn_int_int(void **xpp, size_t nelems, const int *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { int lstatus = ncx_put_int_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #endif #if X_SIZEOF_INT == SIZEOF_LONG /* optimized version */ int ncx_putn_int_long(void **xpp, size_t nelems, const long *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_INT); # else swapn4b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_INT); return ENOERR; } #else int ncx_putn_int_long(void **xpp, size_t nelems, const long *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { int lstatus = ncx_put_int_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #endif int ncx_putn_int_float(void **xpp, size_t nelems, const float *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { int lstatus = ncx_put_int_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_int_double(void **xpp, size_t nelems, const double *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_INT, tp++) { int lstatus = ncx_put_int_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } /* float */ int ncx_getn_float_schar(const void **xpp, size_t nelems, schar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_float_uchar(const void **xpp, size_t nelems, uchar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_float_short(const void **xpp, size_t nelems, short *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_float_int(const void **xpp, size_t nelems, int *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_float_long(const void **xpp, size_t nelems, long *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #if X_SIZEOF_FLOAT == SIZEOF_FLOAT && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_getn_float_float(const void **xpp, size_t nelems, float *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(float)); # else swapn4b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_FLOAT); return ENOERR; } #elif vax int ncx_getn_float_float(const void **xpp, size_t nfloats, float *ip) { float *const end = ip + nfloats; while(ip < end) { struct vax_single *const vsp = (struct vax_single *) ip; const struct ieee_single *const isp = (const struct ieee_single *) (*xpp); unsigned exp = isp->exp_hi << 1 | isp->exp_lo; switch(exp) { case 0 : /* ieee subnormal */ if(isp->mant_hi == min.ieee.mant_hi && isp->mant_lo_hi == min.ieee.mant_lo_hi && isp->mant_lo_lo == min.ieee.mant_lo_lo) { *vsp = min.s; } else { unsigned mantissa = (isp->mant_hi << 16) | isp->mant_lo_hi << 8 | isp->mant_lo_lo; unsigned tmp = mantissa >> 20; if(tmp >= 4) { vsp->exp = 2; } else if (tmp >= 2) { vsp->exp = 1; } else { *vsp = min.s; break; } /* else */ tmp = mantissa - (1 << (20 + vsp->exp )); tmp <<= 3 - vsp->exp; vsp->mantissa2 = tmp; vsp->mantissa1 = (tmp >> 16); } break; case 0xfe : case 0xff : *vsp = max.s; break; default : vsp->exp = exp - IEEE_SNG_BIAS + VAX_SNG_BIAS; vsp->mantissa2 = isp->mant_lo_hi << 8 | isp->mant_lo_lo; vsp->mantissa1 = isp->mant_hi; } vsp->sign = isp->sign; ip++; *xpp = (char *)(*xpp) + X_SIZEOF_FLOAT; } return ENOERR; } #elif _SX && _FLOAT2 int ncx_getn_float_float(const void **xpp, size_t nelems, float *tp) { const char *const xp = *xpp; const int ncnv = ie3_fl2(xp, tp, 4, 8, nelems); *xpp = xp + nelems * X_SIZEOF_FLOAT; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_getn_float_float(const void **xpp, size_t nelems, float *tp) { const char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #endif int ncx_getn_float_double(const void **xpp, size_t nelems, double *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { const int lstatus = ncx_get_float_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_putn_float_schar(void **xpp, size_t nelems, const schar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_float_uchar(void **xpp, size_t nelems, const uchar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_float_short(void **xpp, size_t nelems, const short *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_float_int(void **xpp, size_t nelems, const int *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_float_long(void **xpp, size_t nelems, const long *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #if X_SIZEOF_FLOAT == SIZEOF_FLOAT && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_putn_float_float(void **xpp, size_t nelems, const float *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_FLOAT); # else swapn4b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_FLOAT); return ENOERR; } #elif vax int ncx_putn_float_float(void **xpp, size_t nfloats, const float *ip) { const float *const end = ip + nfloats; while(ip < end) { const struct vax_single *const vsp = (const struct vax_single *)ip; struct ieee_single *const isp = (struct ieee_single *) (*xpp); switch(vsp->exp){ case 0 : /* all vax float with zero exponent map to zero */ *isp = min.ieee; break; case 2 : case 1 : { /* These will map to subnormals */ unsigned mantissa = (vsp->mantissa1 << 16) | vsp->mantissa2; mantissa >>= 3 - vsp->exp; mantissa += (1 << (20 + vsp->exp)); isp->mant_lo_lo = mantissa; isp->mant_lo_hi = mantissa >> 8; isp->mant_hi = mantissa >> 16; isp->exp_lo = 0; isp->exp_hi = 0; } break; case 0xff : /* max.s.exp */ if( vsp->mantissa2 == max.s.mantissa2 && vsp->mantissa1 == max.s.mantissa1) { /* map largest vax float to ieee infinity */ *isp = max.ieee; break; } /* else, fall thru */ default : { unsigned exp = vsp->exp - VAX_SNG_BIAS + IEEE_SNG_BIAS; isp->exp_hi = exp >> 1; isp->exp_lo = exp; isp->mant_lo_lo = vsp->mantissa2; isp->mant_lo_hi = vsp->mantissa2 >> 8; isp->mant_hi = vsp->mantissa1; } } isp->sign = vsp->sign; ip++; *xpp = (char *)(*xpp) + X_SIZEOF_FLOAT; } return ENOERR; } #elif _SX && _FLOAT2 int ncx_putn_float_float(void **xpp, size_t nelems, const float *tp) { char *const xp = *xpp; const int ncnv = fl2_ie3(tp, xp, 8, 4, nelems); *xpp = xp + nelems * X_SIZEOF_FLOAT; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_putn_float_float(void **xpp, size_t nelems, const float *tp) { char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #endif int ncx_putn_float_double(void **xpp, size_t nelems, const double *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_FLOAT, tp++) { int lstatus = ncx_put_float_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } /* double */ int ncx_getn_double_schar(const void **xpp, size_t nelems, schar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_double_uchar(const void **xpp, size_t nelems, uchar *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_double_short(const void **xpp, size_t nelems, short *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_double_int(const void **xpp, size_t nelems, int *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_double_long(const void **xpp, size_t nelems, long *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } int ncx_getn_double_float(const void **xpp, size_t nelems, float *tp) { const char *xp = (const char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #if X_SIZEOF_DOUBLE == SIZEOF_DOUBLE && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_getn_double_double(const void **xpp, size_t nelems, double *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(tp, *xpp, nelems * sizeof(double)); # else swapn8b(tp, *xpp, nelems); # endif *xpp = (const void *)((const char *)(*xpp) + nelems * X_SIZEOF_DOUBLE); return ENOERR; } #elif vax int ncx_getn_double_double(const void **xpp, size_t ndoubles, double *ip) { double *const end = ip + ndoubles; while(ip < end) { struct vax_double *const vdp = (struct vax_double *)ip; const struct ieee_double *const idp = (const struct ieee_double *) (*xpp); { const struct dbl_limits *lim; int ii; for (ii = 0, lim = dbl_limits; ii < sizeof(dbl_limits)/sizeof(struct dbl_limits); ii++, lim++) { if ((idp->mant_lo == lim->ieee.mant_lo) && (idp->mant_4 == lim->ieee.mant_4) && (idp->mant_5 == lim->ieee.mant_5) && (idp->mant_6 == lim->ieee.mant_6) && (idp->exp_lo == lim->ieee.exp_lo) && (idp->exp_hi == lim->ieee.exp_hi) ) { *vdp = lim->d; goto doneit; } } } { unsigned exp = idp->exp_hi << 4 | idp->exp_lo; vdp->exp = exp - IEEE_DBL_BIAS + VAX_DBL_BIAS; } { unsigned mant_hi = ((idp->mant_6 << 16) | (idp->mant_5 << 8) | idp->mant_4); unsigned mant_lo = SWAP4(idp->mant_lo); vdp->mantissa1 = (mant_hi >> 13); vdp->mantissa2 = ((mant_hi & MASK(13)) << 3) | (mant_lo >> 29); vdp->mantissa3 = (mant_lo >> 13); vdp->mantissa4 = (mant_lo << 3); } doneit: vdp->sign = idp->sign; ip++; *xpp = (char *)(*xpp) + X_SIZEOF_DOUBLE; } return ENOERR; } /* vax */ #elif _SX && _FLOAT2 int ncx_getn_double_double(const void **xpp, size_t nelems, double *tp) { const char *const xp = *xpp; const int ncnv = ie3_fl2(xp, tp, 8, 8, nelems); *xpp = xp + nelems * X_SIZEOF_DOUBLE; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_getn_double_double(const void **xpp, size_t nelems, double *tp) { const char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { const int lstatus = ncx_get_double_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (const void *)xp; return status; } #endif int ncx_putn_double_schar(void **xpp, size_t nelems, const schar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_schar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_double_uchar(void **xpp, size_t nelems, const uchar *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_uchar(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_double_short(void **xpp, size_t nelems, const short *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_short(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_double_int(void **xpp, size_t nelems, const int *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_int(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_double_long(void **xpp, size_t nelems, const long *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_long(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } int ncx_putn_double_float(void **xpp, size_t nelems, const float *tp) { char *xp = (char *) *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_float(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #if X_SIZEOF_DOUBLE == SIZEOF_DOUBLE && !defined(NO_IEEE_FLOAT) /* optimized version */ int ncx_putn_double_double(void **xpp, size_t nelems, const double *tp) { #ifdef WORDS_BIGENDIAN (void) memcpy(*xpp, tp, nelems * X_SIZEOF_DOUBLE); # else swapn8b(*xpp, tp, nelems); # endif *xpp = (void *)((char *)(*xpp) + nelems * X_SIZEOF_DOUBLE); return ENOERR; } #elif vax int ncx_putn_double_double(void **xpp, size_t ndoubles, const double *ip) { const double *const end = ip + ndoubles; while(ip < end) { const struct vax_double *const vdp = (const struct vax_double *)ip; struct ieee_double *const idp = (struct ieee_double *) (*xpp); if ((vdp->mantissa4 > (dbl_limits[0].d.mantissa4 - 3)) && (vdp->mantissa3 == dbl_limits[0].d.mantissa3) && (vdp->mantissa2 == dbl_limits[0].d.mantissa2) && (vdp->mantissa1 == dbl_limits[0].d.mantissa1) && (vdp->exp == dbl_limits[0].d.exp)) { *idp = dbl_limits[0].ieee; goto shipit; } if ((vdp->mantissa4 == dbl_limits[1].d.mantissa4) && (vdp->mantissa3 == dbl_limits[1].d.mantissa3) && (vdp->mantissa2 == dbl_limits[1].d.mantissa2) && (vdp->mantissa1 == dbl_limits[1].d.mantissa1) && (vdp->exp == dbl_limits[1].d.exp)) { *idp = dbl_limits[1].ieee; goto shipit; } { unsigned exp = vdp->exp - VAX_DBL_BIAS + IEEE_DBL_BIAS; unsigned mant_lo = ((vdp->mantissa2 & MASK(3)) << 29) | (vdp->mantissa3 << 13) | ((vdp->mantissa4 >> 3) & MASK(13)); unsigned mant_hi = (vdp->mantissa1 << 13) | (vdp->mantissa2 >> 3); if((vdp->mantissa4 & 7) > 4) { /* round up */ mant_lo++; if(mant_lo == 0) { mant_hi++; if(mant_hi > 0xffffff) { mant_hi = 0; exp++; } } } idp->mant_lo = SWAP4(mant_lo); idp->mant_6 = mant_hi >> 16; idp->mant_5 = (mant_hi & 0xff00) >> 8; idp->mant_4 = mant_hi; idp->exp_hi = exp >> 4; idp->exp_lo = exp; } shipit: idp->sign = vdp->sign; ip++; *xpp = (char *)(*xpp) + X_SIZEOF_DOUBLE; } return ENOERR; } /* vax */ #elif _SX && _FLOAT2 int ncx_putn_double_double(void **xpp, size_t nelems, const double *tp) { char *const xp = *xpp; const int ncnv = fl2_ie3(tp, xp, 8, 8, nelems); *xpp = xp + nelems * X_SIZEOF_DOUBLE; return (nelems == ncnv ? ENOERR : NC_ERANGE); } #else int ncx_putn_double_double(void **xpp, size_t nelems, const double *tp) { char *xp = *xpp; int status = ENOERR; for( ; nelems != 0; nelems--, xp += X_SIZEOF_DOUBLE, tp++) { int lstatus = ncx_put_double_double(xp, tp); if(lstatus != ENOERR) status = lstatus; } *xpp = (void *)xp; return status; } #endif /* * Other aggregate conversion functions. */ /* text */ int ncx_getn_text(const void **xpp, size_t nelems, char *tp) { (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_pad_getn_text(const void **xpp, size_t nelems, char *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems + rndup); return ENOERR; } int ncx_putn_text(void **xpp, size_t nelems, const char *tp) { (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_pad_putn_text(void **xpp, size_t nelems, const char *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); if(rndup) { (void) memcpy(*xpp, nada, rndup); *xpp = (void *)((char *)(*xpp) + rndup); } return ENOERR; } /* opaque */ int ncx_getn_void(const void **xpp, size_t nelems, void *tp) { (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_pad_getn_void(const void **xpp, size_t nelems, void *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(tp, *xpp, nelems); *xpp = (void *)((char *)(*xpp) + nelems + rndup); return ENOERR; } int ncx_putn_void(void **xpp, size_t nelems, const void *tp) { (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); return ENOERR; } int ncx_pad_putn_void(void **xpp, size_t nelems, const void *tp) { size_t rndup = nelems % X_ALIGN; if(rndup) rndup = X_ALIGN - rndup; (void) memcpy(*xpp, tp, nelems); *xpp = (void *)((char *)(*xpp) + nelems); if(rndup) { (void) memcpy(*xpp, nada, rndup); *xpp = (void *)((char *)(*xpp) + rndup); } return ENOERR; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/COPYRIGHT0000644000175000017500000000353711606020250021763 0ustar amckinstryamckinstryCopyright 1993-2004 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. xdmf-2.1.dfsg.1/Utilities/vtknetcdf/ncio.h0000644000175000017500000000701011606020250021557 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: ncio.h,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #ifndef _NCIO_H_ #define _NCIO_H_ #include "ncconfig.h" #include /* size_t */ #ifndef NO_SYS_TYPES_H # include /* off_t */ #endif /* NO_SYS_TYPES_H */ #include "netcdf.h" typedef struct ncio ncio; /* forward reference */ /* * A value which is an invalid off_t */ #define OFF_NONE ((off_t)(-1)) /* * Flags used by the region layer, * 'rflags' argument to ncio.rel() and ncio.get(). */ #define RGN_NOLOCK 0x1 /* Don't lock region. * Used when contention control handled * elsewhere. */ #define RGN_NOWAIT 0x2 /* return immediate if can't lock, else wait */ #define RGN_WRITE 0x4 /* we intend to modify, else read only */ #define RGN_MODIFIED 0x8 /* we did modify, else, discard */ /* * The next four typedefs define the signatures * of function pointers in struct ncio below. * They are not used outside of this file and ncio.h, * They just make some casts in the ncio.c more readable. */ /* * Indicate that you are done with the region which begins * at offset. Only reasonable flag value is RGN_MODIFIED. */ typedef int ncio_relfunc(ncio *const nciop, off_t offset, int rflags); /* * Request that the region (offset, extent) * be made available through *vpp. */ typedef int ncio_getfunc(ncio *const nciop, off_t offset, size_t extent, int rflags, void **const vpp); /* * Like memmove(), safely move possibly overlapping data. * Only reasonable flag value is RGN_NOLOCK. */ typedef int ncio_movefunc(ncio *const nciop, off_t to, off_t from, size_t nbytes, int rflags); /* * Write out any dirty buffers to disk and * ensure that next read will get data from disk. */ typedef int ncio_syncfunc(ncio *const nciop); /* * Don't call this. * Internal function called at close to * free up anything hanging off pvt; */ typedef void ncio_freefunc(void *const pvt); /* Get around cplusplus "const xxx in class ncio without constructor" error */ #if defined(__cplusplus) #define NCIO_CONST #else #define NCIO_CONST const #endif /* * netcdf i/o abstraction */ struct ncio { /* * A copy of the ioflags argument passed in to ncio_open() * or ncio_create(). */ int ioflags; /* * The file descriptor of the netcdf file. * This gets handed to the user as the netcdf id. */ NCIO_CONST int fd; /* member functions do the work */ ncio_relfunc *NCIO_CONST rel; ncio_getfunc *NCIO_CONST get; ncio_movefunc *NCIO_CONST move; ncio_syncfunc *NCIO_CONST sync; ncio_freefunc *NCIO_CONST free; /* Implementation private */ /* * A copy of the 'path' argument passed in to ncio_open() * or ncio_create(). Used by ncabort() to remove (unlink) * the file and by error messages. */ const char *path; /* implementation private stuff */ void *NCIO_CONST pvt; }; #undef NCIO_CONST extern int ncio_create(const char *path, int ioflags, size_t initialsz, off_t igeto, size_t igetsz, size_t *sizehintp, ncio **nciopp, void **const igetvpp); extern int ncio_open(const char *path, int ioflags, off_t igeto, size_t igetsz, size_t *sizehintp, ncio **nciopp, void **const igetvpp); extern int ncio_close(ncio *nciop, int doUnlink); extern int ncio_filesize(ncio *nciop, off_t *filesizep); extern int ncio_pad_length(ncio *nciop, off_t length); #endif /* _NCIO_H_ */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/netcdf3.h0000755000175000017500000005127211606020250022171 0ustar amckinstryamckinstry/* * Copyright 1993-1996 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. 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. */ /* "$Id: netcdf3.h,v 1.1 2010-01-06 16:34:07 kwleiter Exp $" */ #ifndef _NETCDF3_ #define _NETCDF3_ #include /* size_t, ptrdiff_t */ #include /* netcdf functions sometimes return system errors */ #include "netcdf.h" #if defined(__cplusplus) extern "C" { #endif /* * The Interface */ /* Declaration modifiers for DLL support (MSC et al) */ #if defined(DLL_NETCDF) /* define when library is a DLL */ # if defined(DLL_EXPORT) /* define when building the library */ # define MSC_EXTRA __declspec(dllexport) # else # define MSC_EXTRA __declspec(dllimport) # endif #else #define MSC_EXTRA #endif /* defined(DLL_NETCDF) */ # define EXTERNL extern MSC_EXTRA EXTERNL const char * nc3_inq_libvers(void); EXTERNL const char * nc3_strerror(int ncerr1); EXTERNL int nc3__create(const char *path, int cmode, size_t initialsz, size_t *chunksizehintp, int *ncidp); EXTERNL int nc3_create(const char *path, int cmode, int *ncidp); EXTERNL int nc3__open(const char *path, int mode, size_t *chunksizehintp, int *ncidp); EXTERNL int nc3_open(const char *path, int mode, int *ncidp); EXTERNL int nc3_set_fill(int ncid, int fillmode, int *old_modep); EXTERNL int nc3_set_default_format(int format, int *old_formatp); EXTERNL int nc3_inq_format(int ncid, int *formatp); EXTERNL int nc3_redef(int ncid); EXTERNL int nc3__enddef(int ncid, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align); EXTERNL int nc3_enddef(int ncid); EXTERNL int nc3_sync(int ncid); EXTERNL int nc3_abort(int ncid); EXTERNL int nc3_close(int ncid); EXTERNL int nc3_inq(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *unlimdimidp); EXTERNL int nc3_inq_ndims(int ncid, int *ndimsp); EXTERNL int nc3_inq_nvars(int ncid, int *nvarsp); EXTERNL int nc3_inq_natts(int ncid, int *nattsp); EXTERNL int nc3_inq_unlimdim(int ncid, int *unlimdimidp); /* Begin _dim */ EXTERNL int nc3_def_dim(int ncid, const char *name, size_t len, int *idp); EXTERNL int nc3_inq_dimid(int ncid, const char *name, int *idp); EXTERNL int nc3_inq_dim(int ncid, int dimid, char *name, size_t *lenp); EXTERNL int nc3_inq_dimname(int ncid, int dimid, char *name); EXTERNL int nc3_inq_dimlen(int ncid, int dimid, size_t *lenp); EXTERNL int nc3_rename_dim(int ncid, int dimid, const char *name); /* End _dim */ /* Begin _att */ EXTERNL int nc3_inq_att(int ncid, int varid, const char *name, nc_type *xtypep, size_t *lenp); EXTERNL int nc3_inq_attid(int ncid, int varid, const char *name, int *idp); EXTERNL int nc3_inq_atttype(int ncid, int varid, const char *name, nc_type *xtypep); EXTERNL int nc3_inq_attlen(int ncid, int varid, const char *name, size_t *lenp); EXTERNL int nc3_inq_attname(int ncid, int varid, int attnum, char *name); EXTERNL int nc3_copy_att(int ncid_in, int varid_in, const char *name, int ncid_out, int varid_out); EXTERNL int nc3_rename_att(int ncid, int varid, const char *name, const char *newname); EXTERNL int nc3_del_att(int ncid, int varid, const char *name); /* End _att */ /* Begin {put,get}_att */ EXTERNL int nc3_put_att_text(int ncid, int varid, const char *name, size_t len, const char *op); EXTERNL int nc3_get_att_text(int ncid, int varid, const char *name, char *ip); EXTERNL int nc3_put_att_uchar(int ncid, int varid, const char *name, nc_type xtype, size_t len, const unsigned char *op); EXTERNL int nc3_get_att_uchar(int ncid, int varid, const char *name, unsigned char *ip); EXTERNL int nc3_put_att_schar(int ncid, int varid, const char *name, nc_type xtype, size_t len, const signed char *op); EXTERNL int nc3_get_att_schar(int ncid, int varid, const char *name, signed char *ip); EXTERNL int nc3_put_att_short(int ncid, int varid, const char *name, nc_type xtype, size_t len, const short *op); EXTERNL int nc3_get_att_short(int ncid, int varid, const char *name, short *ip); EXTERNL int nc3_put_att_int(int ncid, int varid, const char *name, nc_type xtype, size_t len, const int *op); EXTERNL int nc3_get_att_int(int ncid, int varid, const char *name, int *ip); EXTERNL int nc3_put_att_long(int ncid, int varid, const char *name, nc_type xtype, size_t len, const long *op); EXTERNL int nc3_get_att_long(int ncid, int varid, const char *name, long *ip); EXTERNL int nc3_put_att_float(int ncid, int varid, const char *name, nc_type xtype, size_t len, const float *op); EXTERNL int nc3_get_att_float(int ncid, int varid, const char *name, float *ip); EXTERNL int nc3_put_att_double(int ncid, int varid, const char *name, nc_type xtype, size_t len, const double *op); EXTERNL int nc3_get_att_double(int ncid, int varid, const char *name, double *ip); /* End {put,get}_att */ /* Begin _var */ EXTERNL int nc3_def_var(int ncid, const char *name, nc_type xtype, int ndims, const int *dimidsp, int *varidp); EXTERNL int nc3_inq_var(int ncid, int varid, char *name, nc_type *xtypep, int *ndimsp, int *dimidsp, int *nattsp); EXTERNL int nc3_inq_varid(int ncid, const char *name, int *varidp); EXTERNL int nc3_inq_varname(int ncid, int varid, char *name); EXTERNL int nc3_inq_vartype(int ncid, int varid, nc_type *xtypep); EXTERNL int nc3_inq_varndims(int ncid, int varid, int *ndimsp); EXTERNL int nc3_inq_vardimid(int ncid, int varid, int *dimidsp); EXTERNL int nc3_inq_varnatts(int ncid, int varid, int *nattsp); EXTERNL int nc3_rename_var(int ncid, int varid, const char *name); EXTERNL int nc3_copy_var(int ncid_in, int varid, int ncid_out); #ifndef ncvarcpy /* support the old name for now */ #define ncvarcpy(ncid_in, varid, ncid_out) ncvarcopy((ncid_in), (varid), (ncid_out)) #endif /* End _var */ /* Begin {put,get}_var1 */ EXTERNL int nc3_put_var1_text(int ncid, int varid, const size_t *indexp, const char *op); EXTERNL int nc3_get_var1_text(int ncid, int varid, const size_t *indexp, char *ip); EXTERNL int nc3_put_var1_uchar(int ncid, int varid, const size_t *indexp, const unsigned char *op); EXTERNL int nc3_get_var1_uchar(int ncid, int varid, const size_t *indexp, unsigned char *ip); EXTERNL int nc3_put_var1_schar(int ncid, int varid, const size_t *indexp, const signed char *op); EXTERNL int nc3_get_var1_schar(int ncid, int varid, const size_t *indexp, signed char *ip); EXTERNL int nc3_put_var1_short(int ncid, int varid, const size_t *indexp, const short *op); EXTERNL int nc3_get_var1_short(int ncid, int varid, const size_t *indexp, short *ip); EXTERNL int nc3_put_var1_int(int ncid, int varid, const size_t *indexp, const int *op); EXTERNL int nc3_get_var1_int(int ncid, int varid, const size_t *indexp, int *ip); EXTERNL int nc3_put_var1_long(int ncid, int varid, const size_t *indexp, const long *op); EXTERNL int nc3_get_var1_long(int ncid, int varid, const size_t *indexp, long *ip); EXTERNL int nc3_put_var1_float(int ncid, int varid, const size_t *indexp, const float *op); EXTERNL int nc3_get_var1_float(int ncid, int varid, const size_t *indexp, float *ip); EXTERNL int nc3_put_var1_double(int ncid, int varid, const size_t *indexp, const double *op); EXTERNL int nc3_get_var1_double(int ncid, int varid, const size_t *indexp, double *ip); /* End {put,get}_var1 */ /* Begin {put,get}_vara */ EXTERNL int nc3_put_vara_text(int ncid, int varid, const size_t *startp, const size_t *countp, const char *op); EXTERNL int nc3_get_vara_text(int ncid, int varid, const size_t *startp, const size_t *countp, char *ip); EXTERNL int nc3_put_vara_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const unsigned char *op); EXTERNL int nc3_get_vara_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, unsigned char *ip); EXTERNL int nc3_put_vara_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const signed char *op); EXTERNL int nc3_get_vara_schar(int ncid, int varid, const size_t *startp, const size_t *countp, signed char *ip); EXTERNL int nc3_put_vara_short(int ncid, int varid, const size_t *startp, const size_t *countp, const short *op); EXTERNL int nc3_get_vara_short(int ncid, int varid, const size_t *startp, const size_t *countp, short *ip); EXTERNL int nc3_put_vara_int(int ncid, int varid, const size_t *startp, const size_t *countp, const int *op); EXTERNL int nc3_get_vara_int(int ncid, int varid, const size_t *startp, const size_t *countp, int *ip); EXTERNL int nc3_put_vara_long(int ncid, int varid, const size_t *startp, const size_t *countp, const long *op); EXTERNL int nc3_get_vara_long(int ncid, int varid, const size_t *startp, const size_t *countp, long *ip); EXTERNL int nc3_put_vara_float(int ncid, int varid, const size_t *startp, const size_t *countp, const float *op); EXTERNL int nc3_get_vara_float(int ncid, int varid, const size_t *startp, const size_t *countp, float *ip); EXTERNL int nc3_put_vara_double(int ncid, int varid, const size_t *startp, const size_t *countp, const double *op); EXTERNL int nc3_get_vara_double(int ncid, int varid, const size_t *startp, const size_t *countp, double *ip); /* End {put,get}_vara */ /* Begin {put,get}_vars */ EXTERNL int nc3_put_vars_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const char *op); EXTERNL int nc3_get_vars_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, char *ip); EXTERNL int nc3_put_vars_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const unsigned char *op); EXTERNL int nc3_get_vars_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, unsigned char *ip); EXTERNL int nc3_put_vars_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const signed char *op); EXTERNL int nc3_get_vars_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, signed char *ip); EXTERNL int nc3_put_vars_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const short *op); EXTERNL int nc3_get_vars_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, short *ip); EXTERNL int nc3_put_vars_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const int *op); EXTERNL int nc3_get_vars_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, int *ip); EXTERNL int nc3_put_vars_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const long *op); EXTERNL int nc3_get_vars_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, long *ip); EXTERNL int nc3_put_vars_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const float *op); EXTERNL int nc3_get_vars_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, float *ip); EXTERNL int nc3_put_vars_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const double *op); EXTERNL int nc3_get_vars_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, double *ip); /* End {put,get}_vars */ /* Begin {put,get}_varm */ EXTERNL int nc3_put_varm_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const char *op); EXTERNL int nc3_get_varm_text(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, char *ip); EXTERNL int nc3_put_varm_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const unsigned char *op); EXTERNL int nc3_get_varm_uchar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, unsigned char *ip); EXTERNL int nc3_put_varm_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const signed char *op); EXTERNL int nc3_get_varm_schar(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, signed char *ip); EXTERNL int nc3_put_varm_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const short *op); EXTERNL int nc3_get_varm_short(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, short *ip); EXTERNL int nc3_put_varm_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const int *op); EXTERNL int nc3_get_varm_int(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, int *ip); EXTERNL int nc3_put_varm_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const long *op); EXTERNL int nc3_get_varm_long(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, long *ip); EXTERNL int nc3_put_varm_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const float *op); EXTERNL int nc3_get_varm_float(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, float *ip); EXTERNL int nc3_put_varm_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t *imapp, const double *op); EXTERNL int nc3_get_varm_double(int ncid, int varid, const size_t *startp, const size_t *countp, const ptrdiff_t *stridep, const ptrdiff_t * imap, double *ip); /* End {put,get}_varm */ /* Begin {put,get}_var */ EXTERNL int nc3_put_var_text(int ncid, int varid, const char *op); EXTERNL int nc3_get_var_text(int ncid, int varid, char *ip); EXTERNL int nc3_put_var_uchar(int ncid, int varid, const unsigned char *op); EXTERNL int nc3_get_var_uchar(int ncid, int varid, unsigned char *ip); EXTERNL int nc3_put_var_schar(int ncid, int varid, const signed char *op); EXTERNL int nc3_get_var_schar(int ncid, int varid, signed char *ip); EXTERNL int nc3_put_var_short(int ncid, int varid, const short *op); EXTERNL int nc3_get_var_short(int ncid, int varid, short *ip); EXTERNL int nc3_put_var_int(int ncid, int varid, const int *op); EXTERNL int nc3_get_var_int(int ncid, int varid, int *ip); EXTERNL int nc3_put_var_long(int ncid, int varid, const long *op); EXTERNL int nc3_get_var_long(int ncid, int varid, long *ip); EXTERNL int nc3_put_var_float(int ncid, int varid, const float *op); EXTERNL int nc3_get_var_float(int ncid, int varid, float *ip); EXTERNL int nc3_put_var_double(int ncid, int varid, const double *op); EXTERNL int nc3_get_var_double(int ncid, int varid, double *ip); /* End {put,get}_var */ /* #ifdef _CRAYMPP */ /* * Public interfaces to better support * CRAY multi-processor systems like T3E. * A tip of the hat to NERSC. */ /* * It turns out we need to declare and define * these public interfaces on all platforms * or things get ugly working out the * FORTRAN interface. On !_CRAYMPP platforms, * these functions work as advertised, but you * can only use "processor element" 0. */ EXTERNL int nc3__create_mp(const char *path, int cmode, size_t initialsz, int basepe, size_t *chunksizehintp, int *ncidp); EXTERNL int nc3__open_mp(const char *path, int mode, int basepe, size_t *chunksizehintp, int *ncidp); EXTERNL int nc3_delete_mp(const char * path, int basepe); EXTERNL int nc3_set_base_pe(int ncid, int pe); EXTERNL int nc3_inq_base_pe(int ncid, int *pe); /* #endif _CRAYMPP */ /* Begin v2.4 backward compatiblity */ EXTERNL void nc3_advise(const char *cdf_routine_name, int err, const char *fmt,...); /* * C data type corresponding to a netCDF NC_LONG argument, * a signed 32 bit object. * * This is the only thing in this file which architecture dependent. */ EXTERNL int nc3typelen(nc_type datatype); EXTERNL int nc3create(const char* path, int cmode); EXTERNL int nc3open(const char* path, int mode); EXTERNL int nc3setfill(int ncid, int fillmode); EXTERNL int nc3redef(int ncid); EXTERNL int nc3endef(int ncid); EXTERNL int nc3sync(int ncid); EXTERNL int nc3abort(int ncid); EXTERNL int nc3close(int ncid); EXTERNL int nc3inquire(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *unlimdimp); EXTERNL int nc3dimdef(int ncid, const char *name, long len); EXTERNL int nc3dimid(int ncid, const char *name); EXTERNL int nc3diminq(int ncid, int dimid, char *name, long *lenp); EXTERNL int nc3dimrename(int ncid, int dimid, const char *name); EXTERNL int nc3attput(int ncid, int varid, const char *name, nc_type xtype, int len, const void *op); EXTERNL int nc3attinq(int ncid, int varid, const char *name, nc_type *xtypep, int *lenp); EXTERNL int nc3attget(int ncid, int varid, const char *name, void *ip); EXTERNL int nc3attcopy(int ncid_in, int varid_in, const char *name, int ncid_out, int varid_out); EXTERNL int nc3attname(int ncid, int varid, int attnum, char *name); EXTERNL int nc3attrename(int ncid, int varid, const char *name, const char *newname); EXTERNL int nc3attdel(int ncid, int varid, const char *name); EXTERNL int nc3vardef(int ncid, const char *name, nc_type xtype, int ndims, const int *dimidsp); EXTERNL int nc3varid(int ncid, const char *name); EXTERNL int nc3varinq(int ncid, int varid, char *name, nc_type *xtypep, int *ndimsp, int *dimidsp, int *nattsp); EXTERNL int nc3varput1(int ncid, int varid, const long *indexp, const void *op); EXTERNL int nc3varget1(int ncid, int varid, const long *indexp, void *ip); EXTERNL int nc3varput(int ncid, int varid, const long *startp, const long *countp, const void *op); EXTERNL int nc3varget(int ncid, int varid, const long *startp, const long *countp, void *ip); EXTERNL int nc3varputs(int ncid, int varid, const long *startp, const long *countp, const long *stridep, const void *op); EXTERNL int nc3vargets(int ncid, int varid, const long *startp, const long *countp, const long *stridep, void *ip); EXTERNL int nc3varputg(int ncid, int varid, const long *startp, const long *countp, const long *stridep, const long *imapp, const void *op); EXTERNL int nc3vargetg(int ncid, int varid, const long *startp, const long *countp, const long *stridep, const long *imapp, void *ip); EXTERNL int nc3varrename(int ncid, int varid, const char *name); EXTERNL int nc3recinq(int ncid, int *nrecvarsp, int *recvaridsp, long *recsizesp); EXTERNL int nc3recget(int ncid, long recnum, void **datap); EXTERNL int nc3recput(int ncid, long recnum, void *const *datap); /* End v2.4 backward compatiblity */ #endif /*!NO_NETCDF_2*/ #if defined(__cplusplus) } #endif xdmf-2.1.dfsg.1/Utilities/vtknetcdf/CMakeLists.txt0000644000175000017500000001756211606020250023233 0ustar amckinstryamckinstryPROJECT(VTKNETCDF) INCLUDE_REGULAR_EXPRESSION(".*") SET(netcdf_SRCS attr.c dim.c error.c libvers.c nc.c posixio.c ncx.c putget.c string.c v1hpg.c v2i.c var.c ) IF(APPLE) SET_SOURCE_FILES_PROPERTIES( v2i.c PROPERTIES COMPILE_FLAGS -fno-common) ENDIF(APPLE) INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ) # Include all the necessary files for macros INCLUDE (CheckIncludeFiles) INCLUDE (CheckFunctionExists) INCLUDE (CheckTypeSize) INCLUDE (CheckSymbolExists) INCLUDE (TestBigEndian) MACRO(MANGLE_VARIABLE_NAME str var prefix) STRING(TOUPPER "${str}" mangle_variable_name_var) STRING(REGEX REPLACE "[/. ]" "_" mangle_variable_name_var "${mangle_variable_name_var}") SET(${var} "${prefix}${mangle_variable_name_var}") ENDMACRO(MANGLE_VARIABLE_NAME str var) # Check if header file exists and add it to the list. MACRO(CHECK_INCLUDE_FILE_CONCAT FILE) MANGLE_VARIABLE_NAME("${FILE}" "CHECK_INCLUDE_FILE_CONCAT_VAR" "HAVE_") CHECK_INCLUDE_FILES("${HEADER_INCLUDES};${FILE}" ${CHECK_INCLUDE_FILE_CONCAT_VAR}) IF(${CHECK_INCLUDE_FILE_CONCAT_VAR}) SET(HEADER_INCLUDES ${HEADER_INCLUDES} ${FILE}) ENDIF(${CHECK_INCLUDE_FILE_CONCAT_VAR}) ENDMACRO(CHECK_INCLUDE_FILE_CONCAT) MACRO(CHECK_FUNCTION_EXISTS_EX FUNC) MANGLE_VARIABLE_NAME("${FUNC}" "CHECK_FUNCTION_EXISTS_EX_VAR" "HAVE_") CHECK_FUNCTION_EXISTS("${FUNC}" "${CHECK_FUNCTION_EXISTS_EX_VAR}") ENDMACRO(CHECK_FUNCTION_EXISTS_EX) MACRO(CHECK_SYMBOL_EXISTS_EX SYM) MANGLE_VARIABLE_NAME("${SYM}" "CHECK_SYMBOL_EXISTS_EX_VAR" "HAVE_") CHECK_SYMBOL_EXISTS("${SYM}" "${HEADER_INCLUDES}" "${CHECK_SYMBOL_EXISTS_EX_VAR}") ENDMACRO(CHECK_SYMBOL_EXISTS_EX) MACRO(CHECK_TYPE_SIZE_EX type) MANGLE_VARIABLE_NAME("${type}" "check_type_size_var" "") CHECK_TYPE_SIZE("${type}" "SIZEOF_${check_type_size_var}") IF(HAVE_${check_type_size_var}) SET("HAVE_${check_type_size_var}" 1) ENDIF(HAVE_${check_type_size_var}) ENDMACRO(CHECK_TYPE_SIZE_EX) MACRO(C_SOURCE_COMPILES SOURCE VAR) IF("${VAR}" MATCHES "^${VAR}$") SET(MACRO_CHECK_FUNCTION_DEFINITIONS "-D${VAR} ${CMAKE_REQUIRED_FLAGS}") IF(CMAKE_REQUIRED_LIBRARIES) SET(C_SOURCE_COMPILES_ADD_LIBRARIES "-DLINK_LIBRARIES:STRING=${CMAKE_REQUIRED_LIBRARIES}") ENDIF(CMAKE_REQUIRED_LIBRARIES) FILE(WRITE "${CMAKE_BINARY_DIR}/CMakeTmp/src.c" "${SOURCE}") MESSAGE(STATUS "Performing NetCDF Test ${VAR}") TRY_COMPILE(${VAR} ${CMAKE_BINARY_DIR} ${CMAKE_BINARY_DIR}/CMakeTmp/src.c CMAKE_FLAGS "${C_SOURCE_COMPILES_ADD_LIBRARIES}" OUTPUT_VARIABLE OUTPUT) IF(${VAR}) SET(${VAR} 1 CACHE INTERNAL "NetCDF test ${FUNCTION}") MESSAGE(STATUS "Performing NetCDF Test ${VAR} - Success") WRITE_FILE(${CMAKE_BINARY_DIR}/CMakeFiles/CMakeOutput.log "Performing C SOURCE FILE Test ${VAR} succeded with the following output:\n" "${OUTPUT}\n" "Source file was:\n${SOURCE}\n" APPEND) ELSE(${VAR}) MESSAGE(STATUS "Performing NetCDF Test ${VAR} - Failed") SET(${VAR} "" CACHE INTERNAL "NetCDF test ${FUNCTION}") WRITE_FILE(${CMAKE_BINARY_DIR}/CMakeFiles/CMakeError.log "Performing C SOURCE FILE Test ${VAR} failed with the following output:\n" "${OUTPUT}\n" "Source file was:\n${SOURCE}\n" APPEND) ENDIF(${VAR}) ENDIF("${VAR}" MATCHES "^${VAR}$") ENDMACRO(C_SOURCE_COMPILES) CHECK_INCLUDE_FILES("stdlib.h;stdarg.h;string.h;float.h" STDC_HEADERS) FOREACH(file "alloca.h" "stdlib.h" "sys/types.h" "sys/stat.h" "unistd.h" "fcntl.h" "stdio.h" "string.h" "stddef.h" "stdint.h" ) CHECK_INCLUDE_FILE_CONCAT("${file}") ENDFOREACH(file) FOREACH(func alloca strerror ) CHECK_SYMBOL_EXISTS_EX("${func}") ENDFOREACH(func) FOREACH(type "size_t" "ssize_t" "ptrdiff_t" "off_t" "double" "float" "int" "long" "short" "uchar" ) CHECK_TYPE_SIZE_EX("${type}") ENDFOREACH(type) SET(testsrc "#include int main() { return 0; } int t() { struct stat s; s.st_blksize; ; return 0; }") IF(HAVE_SYS_TYPES_H) SET(testsrc "#include \n${testsrc}") ENDIF(HAVE_SYS_TYPES_H) IF(HAVE_SYS_STAT_H) C_SOURCE_COMPILES("${testsrc}" HAVE_ST_BLKSIZE) ENDIF(HAVE_SYS_STAT_H) # SET(testsrc "main() { char* path = tmpnam(NULL); int exitStatus = 1; if (path != NULL) { int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666); if (fd != -1) { if (write(fd, \"0\", 1) == 1) { off_t pos = lseek(fd, 0, SEEK_CUR); if (pos != (off_t)-1) { if (ftruncate(fd, 512) != -1) { if (pos == lseek(fd, 0, SEEK_CUR)) { if (lseek(fd, 0, SEEK_SET) == 0) { char buf[512]; if (read(fd, buf, 512) == 512) exitStatus = 0; } } } } } close(fd); unlink(path); } } return exitStatus; }") IF(HAVE_SYS_TYPES_H) SET(testsrc "#include \n${testsrc}") ENDIF(HAVE_SYS_TYPES_H) IF(HAVE_SYS_STAT_H) SET(testsrc "#include \n${testsrc}") ENDIF(HAVE_SYS_STAT_H) IF(HAVE_FCNTL_H) SET(testsrc "#include \n${testsrc}") ENDIF(HAVE_FCNTL_H) IF(HAVE_STDIO_H) SET(testsrc "#include \n${testsrc}") ENDIF(HAVE_STDIO_H) IF(HAVE_UNISTD_H) SET(testsrc "#include \n${testsrc}") ENDIF(HAVE_UNISTD_H) C_SOURCE_COMPILES("${testsrc}" HAVE_FTRUNCATE) MACRO(INVERT_VARIABLE var val) SET(INVERT_VARIABLE_VAR "${val}") SET(${var} "1") IF(INVERT_VARIABLE_VAR) SET(${var} "0") ENDIF(INVERT_VARIABLE_VAR) ENDMACRO(INVERT_VARIABLE) INVERT_VARIABLE(NO_STDLIB_H "${HAVE_STDLIB_H}") INVERT_VARIABLE(NO_SYS_TYPES_H "${HAVE_SYS_TYPES_H}") INVERT_VARIABLE(NO_STRERROR "${HAVE_STRERROR}") IF(NOT HAVE_SIZEOF_SIZE_T) SET(size_t long) ENDIF(NOT HAVE_SIZEOF_SIZE_T) IF(NOT HAVE_SIZEOF_OFF_T) SET(off_t long) ENDIF(NOT HAVE_SIZEOF_OFF_T) IF(NOT HAVE_SIZEOF_SSIZE_T) SET(ssize_t int) ENDIF(NOT HAVE_SIZEOF_SSIZE_T) IF(NOT HAVE_SIZEOF_PTRDIFF_T) SET(ptrdiff_t int) ENDIF(NOT HAVE_SIZEOF_PTRDIFF_T) IF(NOT HAVE_SIZEOF_UCHAR) SET(uchar "unsigned char") ENDIF(NOT HAVE_SIZEOF_UCHAR) # use the same name for the variable as in VTK, so the result is reused TEST_BIG_ENDIAN(CMAKE_WORDS_BIGENDIAN) SET(WORDS_BIGENDIAN ${CMAKE_WORDS_BIGENDIAN}) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/ncconfig.h.in ${CMAKE_CURRENT_BINARY_DIR}/ncconfig.h @ONLY IMMEDIATE) ADD_LIBRARY(vtkNetCDF ${netcdf_SRCS}) # Take care of symbol export/import on Windows ADD_DEFINITIONS("-DNC_DLL_EXPORT") # Apply user-defined properties to the library target. IF(VTK_LIBRARY_PROPERTIES) SET_TARGET_PROPERTIES(vtkNetCDF PROPERTIES ${VTK_LIBRARY_PROPERTIES}) ENDIF(VTK_LIBRARY_PROPERTIES) IF(NOT VTK_INSTALL_NO_LIBRARIES) IF(NOT VTK_INSTALL_BIN_DIR_CM24) SET(VTK_INSTALL_BIN_DIR_CM24 ${CMAKE_INSTALL_PREFIX}/bin) ENDIF(NOT VTK_INSTALL_BIN_DIR_CM24) IF(NOT VTK_INSTALL_LIB_DIR_CM24) SET(VTK_INSTALL_LIB_DIR_CM24 ${CMAKE_INSTALL_PREFIX}/lib) ENDIF(NOT VTK_INSTALL_LIB_DIR_CM24) IF(NOT VTK_INSTALL_INCLUDE_DIR_CM24) SET(VTK_INSTALL_INCLUDE_DIR_CM24 ${CMAKE_INSTALL_PREFIX}/include) ENDIF(NOT VTK_INSTALL_INCLUDE_DIR_CM24) INSTALL(TARGETS vtkNetCDF RUNTIME DESTINATION ${VTK_INSTALL_BIN_DIR_CM24} COMPONENT RuntimeLibraries LIBRARY DESTINATION ${VTK_INSTALL_LIB_DIR_CM24} COMPONENT RuntimeLibraries ARCHIVE DESTINATION ${VTK_INSTALL_LIB_DIR_CM24} COMPONENT Development) ENDIF(NOT VTK_INSTALL_NO_LIBRARIES) IF(NOT VTK_INSTALL_NO_DEVELOPMENT) INSTALL(FILES ${VTKNETCDF_BINARY_DIR}/ncconfig.h ${VTKNETCDF_SOURCE_DIR}/netcdf.h ${VTKNETCDF_SOURCE_DIR}/netcdf3.h ${VTKNETCDF_SOURCE_DIR}/vtk_netcdf.h ${VTKNETCDF_SOURCE_DIR}/vtk_netcdf_mangle.h DESTINATION ${VTK_INSTALL_INCLUDE_DIR_CM24}/vtknetcdf COMPONENT Development) ENDIF(NOT VTK_INSTALL_NO_DEVELOPMENT) xdmf-2.1.dfsg.1/Utilities/vtknetcdf/ncx.h0000644000175000017500000004673211606020250021435 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* "$Id: ncx.h,v 1.1 2010-01-06 16:34:05 kwleiter Exp $" */ #ifndef _NCX_H_ #define _NCX_H_ /* * An external data representation interface. * * This started out as a general replacement for ONC XDR, * specifically, the xdrmem family of functions. * * We eventually realized that we could write more portable * code if we decoupled any association between the 'C' types * and the external types. (XDR has this association between the 'C' * types and the external representations, like xdr_int() takes * an int argument and goes to an external int representation.) * So, now there is a matrix of functions. * */ #include "ncconfig.h" /* output of 'configure' */ #include "rnd.h" #include /* size_t */ #include #ifndef NO_SYS_TYPES_H # include /* off_t */ #endif /* NO_SYS_TYPES_H */ #include "netcdf.h" #if defined(_CRAY) && !defined(_CRAYIEEE) && !defined(__crayx1) #define CRAYFLOAT 1 /* CRAY Floating point */ #elif defined(_SX) && defined(_FLOAT2) /* NEC SUPER-UX in CRAY mode */ #define CRAYFLOAT 1 /* CRAY Floating point */ #endif /* * The integer return code for the conversion routines * is 0 (ENOERR) when no error occured, or NC_ERANGE as appropriate * for an overflow conversion. */ #ifndef ENOERR #define ENOERR 0 #endif #ifndef NC_ERANGE #define NC_ERANGE (-60) /* N.B. must match value in netcdf.h */ #endif #ifndef NC_ENOMEM #define NC_ENOMEM (-61) /* N.B. must match value in netcdf.h */ #endif /* * External sizes of the primitive elements. */ #define X_SIZEOF_CHAR 1 #define X_SIZEOF_SHORT 2 #define X_SIZEOF_INT 4 /* xdr_int */ #if 0 #define X_SIZEOF_LONG 8 */ /* xdr_long_long */ #endif #define X_SIZEOF_FLOAT 4 #define X_SIZEOF_DOUBLE 8 /* * For now, netcdf is limited to 32 bit sizes, * If compiled with support for "large files", then * netcdf will use a 64 bit off_t and it can then write a file * using 64 bit offsets. * see also X_SIZE_MAX, X_OFF_MAX below */ #define X_SIZEOF_OFF_T (sizeof(off_t)) #define X_SIZEOF_SIZE_T X_SIZEOF_INT /* * limits of the external representation */ #define X_SCHAR_MIN (-128) #define X_SCHAR_MAX 127 #define X_UCHAR_MAX 255U #define X_SHORT_MIN (-32768) #define X_SHRT_MIN X_SHORT_MIN /* alias compatible with limits.h */ #define X_SHORT_MAX 32767 #define X_SHRT_MAX X_SHORT_MAX /* alias compatible with limits.h */ #define X_USHORT_MAX 65535U #define X_USHRT_MAX X_USHORT_MAX /* alias compatible with limits.h */ #define X_INT_MIN (-2147483647-1) #define X_INT_MAX 2147483647 #define X_UINT_MAX 4294967295U #define X_FLOAT_MAX 3.402823466e+38f #define X_FLOAT_MIN (-X_FLOAT_MAX) #define X_FLT_MAX X_FLOAT_MAX /* alias compatible with limits.h */ #if CRAYFLOAT /* ldexp(1. - ldexp(.5 , -46), 1024) */ #define X_DOUBLE_MAX 1.79769313486230e+308 #else /* scalb(1. - scalb(.5 , -52), 1024) */ #define X_DOUBLE_MAX 1.7976931348623157e+308 #endif #define X_DOUBLE_MIN (-X_DOUBLE_MAX) #define X_DBL_MAX X_DOUBLE_MAX /* alias compatible with limits.h */ #define X_SIZE_MAX X_UINT_MAX #define X_OFF_MAX X_INT_MAX /* Begin ncx_len */ /* * ncx_len_xxx() interfaces are defined as macros below, * These give the length of an array of nelems of the type. * N.B. The 'char' and 'short' interfaces give the X_ALIGNED length. */ #define X_ALIGN 4 /* a.k.a. BYTES_PER_XDR_UNIT */ #define ncx_len_char(nelems) \ _RNDUP((nelems), X_ALIGN) #define ncx_len_short(nelems) \ (((nelems) + (nelems)%2) * X_SIZEOF_SHORT) #define ncx_len_int(nelems) \ ((nelems) * X_SIZEOF_INT) #define ncx_len_long(nelems) \ ((nelems) * X_SIZEOF_LONG) #define ncx_len_float(nelems) \ ((nelems) * X_SIZEOF_FLOAT) #define ncx_len_double(nelems) \ ((nelems) * X_SIZEOF_DOUBLE) /* End ncx_len */ #if __CHAR_UNSIGNED__ /* 'char' is unsigned, declare ncbyte as 'signed char' */ typedef signed char schar; #else /* 'char' is signed */ typedef signed char schar; #endif /* __CHAR_UNSIGNED__ */ /* * Primitive numeric conversion functions. * The `put' functions convert from native internal * type to the external type, while the `get' functions * convert from the external to the internal. * * These take the form * int ncx_get_{external_type}_{internal_type}( * const void *xp, * internal_type *ip * ); * int ncx_put_{external_type}_{internal_type}( * void *xp, * const internal_type *ip * ); * where * `external_type' and `internal_type' chosen from schar uchar short ushort int uint long ulong float double * * Not all combinations make sense. * We may not implement all combinations that make sense. * The netcdf functions that use this ncx interface don't * use these primitive conversion functions. They use the * aggregate conversion functions declared below. * * Storage for a single element of external type is at the `void * xp' * argument. * * Storage for a single element of internal type is at `ip' argument. * * These functions return 0 (ENOERR) when no error occured, * or NC_ERANGE when the value being converted is too large. * When NC_ERANGE occurs, an undefined (implementation dependent) * conversion may have occured. * * Note that loss of precision may occur silently. * */ #if 0 extern int ncx_get_schar_schar(const void *xp, schar *ip); extern int ncx_get_schar_uchar(const void *xp, uchar *ip); extern int ncx_get_schar_short(const void *xp, short *ip); extern int ncx_get_schar_int(const void *xp, int *ip); extern int ncx_get_schar_long(const void *xp, long *ip); extern int ncx_get_schar_float(const void *xp, float *ip); extern int ncx_get_schar_double(const void *xp, double *ip); extern int ncx_put_schar_schar(void *xp, const schar *ip); extern int ncx_put_schar_uchar(void *xp, const uchar *ip); extern int ncx_put_schar_short(void *xp, const short *ip); extern int ncx_put_schar_int(void *xp, const int *ip); extern int ncx_put_schar_long(void *xp, const long *ip); extern int ncx_put_schar_float(void *xp, const float *ip); extern int ncx_put_schar_double(void *xp, const double *ip); #endif extern int ncx_get_short_schar(const void *xp, schar *ip); extern int ncx_get_short_uchar(const void *xp, uchar *ip); extern int ncx_get_short_short(const void *xp, short *ip); extern int ncx_get_short_int(const void *xp, int *ip); extern int ncx_get_short_long(const void *xp, long *ip); extern int ncx_get_short_float(const void *xp, float *ip); extern int ncx_get_short_double(const void *xp, double *ip); extern int ncx_put_short_schar(void *xp, const schar *ip); extern int ncx_put_short_uchar(void *xp, const uchar *ip); extern int ncx_put_short_short(void *xp, const short *ip); extern int ncx_put_short_int(void *xp, const int *ip); extern int ncx_put_short_long(void *xp, const long *ip); extern int ncx_put_short_float(void *xp, const float *ip); extern int ncx_put_short_double(void *xp, const double *ip); extern int ncx_get_int_schar(const void *xp, schar *ip); extern int ncx_get_int_uchar(const void *xp, uchar *ip); extern int ncx_get_int_short(const void *xp, short *ip); extern int ncx_get_int_int(const void *xp, int *ip); extern int ncx_get_int_long(const void *xp, long *ip); extern int ncx_get_int_float(const void *xp, float *ip); extern int ncx_get_int_double(const void *xp, double *ip); extern int ncx_put_int_schar(void *xp, const schar *ip); extern int ncx_put_int_uchar(void *xp, const uchar *ip); extern int ncx_put_int_short(void *xp, const short *ip); extern int ncx_put_int_int(void *xp, const int *ip); extern int ncx_put_int_long(void *xp, const long *ip); extern int ncx_put_int_float(void *xp, const float *ip); extern int ncx_put_int_double(void *xp, const double *ip); extern int ncx_get_float_schar(const void *xp, schar *ip); extern int ncx_get_float_uchar(const void *xp, uchar *ip); extern int ncx_get_float_short(const void *xp, short *ip); extern int ncx_get_float_int(const void *xp, int *ip); extern int ncx_get_float_long(const void *xp, long *ip); extern int ncx_get_float_float(const void *xp, float *ip); extern int ncx_get_float_double(const void *xp, double *ip); extern int ncx_put_float_schar(void *xp, const schar *ip); extern int ncx_put_float_uchar(void *xp, const uchar *ip); extern int ncx_put_float_short(void *xp, const short *ip); extern int ncx_put_float_int(void *xp, const int *ip); extern int ncx_put_float_long(void *xp, const long *ip); extern int ncx_put_float_float(void *xp, const float *ip); extern int ncx_put_float_double(void *xp, const double *ip); extern int ncx_get_double_schar(const void *xp, schar *ip); extern int ncx_get_double_uchar(const void *xp, uchar *ip); extern int ncx_get_double_short(const void *xp, short *ip); extern int ncx_get_double_int(const void *xp, int *ip); extern int ncx_get_double_long(const void *xp, long *ip); extern int ncx_get_double_float(const void *xp, float *ip); extern int ncx_get_double_double(const void *xp, double *ip); extern int ncx_put_double_schar(void *xp, const schar *ip); extern int ncx_put_double_uchar(void *xp, const uchar *ip); extern int ncx_put_double_short(void *xp, const short *ip); extern int ncx_put_double_int(void *xp, const int *ip); extern int ncx_put_double_long(void *xp, const long *ip); extern int ncx_put_double_float(void *xp, const float *ip); extern int ncx_put_double_double(void *xp, const double *ip); /* * Other primitive conversion functions * N.B. slightly different interface * Used by netcdf. */ /* ncx_get_int_size_t */ extern int ncx_get_size_t(const void **xpp, size_t *ulp); /* ncx_get_int_off_t */ extern int ncx_get_off_t(const void **xpp, off_t *lp, size_t sizeof_off_t); /* ncx_put_int_size_t */ extern int ncx_put_size_t(void **xpp, const size_t *ulp); /* ncx_put_int_off_t */ extern int ncx_put_off_t(void **xpp, const off_t *lp, size_t sizeof_off_t); /* * Aggregate numeric conversion functions. * Convert an array. Replaces xdr_array(...). * These functions are used by netcdf. Unlike the xdr * interface, we optimize for aggregate conversions. * This functions should be implemented to take advantage * of multiple processor / parallel hardware where available. * * These take the form * int ncx_getn_{external_type}_{internal_type}( * const void *xpp, * size_t nelems, * internal_type *ip * ); * int ncx_putn_{external_type}_{internal_type}( * void **xpp, * size_t nelems, * const internal_type *ip * ); * Where the types are as in the primitive numeric conversion functions. * * The value of the pointer to pointer argument, *xpp, is * expected to reference storage for `nelems' of the external * type. On return, it modified to reference just past the last * converted external element. * * The types whose external size is less than X_ALIGN also have `pad' * interfaces. These round (and zero fill on put) *xpp up to X_ALIGN * boundaries. (This is the usual xdr behavior.) * * The `ip' argument should point to an array of `nelems' of * internal_type. * * Range errors (NC_ERANGE) for a individual values in the array * DO NOT terminate the array conversion. All elements are converted, * with some having undefined values. * If any range error occurs, the function returns NC_ERANGE. * */ extern int ncx_getn_schar_schar(const void **xpp, size_t nelems, schar *ip); extern int ncx_getn_schar_uchar(const void **xpp, size_t nelems, uchar *ip); extern int ncx_getn_schar_short(const void **xpp, size_t nelems, short *ip); extern int ncx_getn_schar_int(const void **xpp, size_t nelems, int *ip); extern int ncx_getn_schar_long(const void **xpp, size_t nelems, long *ip); extern int ncx_getn_schar_float(const void **xpp, size_t nelems, float *ip); extern int ncx_getn_schar_double(const void **xpp, size_t nelems, double *ip); extern int ncx_pad_getn_schar_schar(const void **xpp, size_t nelems, schar *ip); extern int ncx_pad_getn_schar_uchar(const void **xpp, size_t nelems, uchar *ip); extern int ncx_pad_getn_schar_short(const void **xpp, size_t nelems, short *ip); extern int ncx_pad_getn_schar_int(const void **xpp, size_t nelems, int *ip); extern int ncx_pad_getn_schar_long(const void **xpp, size_t nelems, long *ip); extern int ncx_pad_getn_schar_float(const void **xpp, size_t nelems, float *ip); extern int ncx_pad_getn_schar_double(const void **xpp, size_t nelems, double *ip); extern int ncx_putn_schar_schar(void **xpp, size_t nelems, const schar *ip); extern int ncx_putn_schar_uchar(void **xpp, size_t nelems, const uchar *ip); extern int ncx_putn_schar_short(void **xpp, size_t nelems, const short *ip); extern int ncx_putn_schar_int(void **xpp, size_t nelems, const int *ip); extern int ncx_putn_schar_long(void **xpp, size_t nelems, const long *ip); extern int ncx_putn_schar_float(void **xpp, size_t nelems, const float *ip); extern int ncx_putn_schar_double(void **xpp, size_t nelems, const double *ip); extern int ncx_pad_putn_schar_schar(void **xpp, size_t nelems, const schar *ip); extern int ncx_pad_putn_schar_uchar(void **xpp, size_t nelems, const uchar *ip); extern int ncx_pad_putn_schar_short(void **xpp, size_t nelems, const short *ip); extern int ncx_pad_putn_schar_int(void **xpp, size_t nelems, const int *ip); extern int ncx_pad_putn_schar_long(void **xpp, size_t nelems, const long *ip); extern int ncx_pad_putn_schar_float(void **xpp, size_t nelems, const float *ip); extern int ncx_pad_putn_schar_double(void **xpp, size_t nelems, const double *ip); extern int ncx_getn_short_schar(const void **xpp, size_t nelems, schar *ip); extern int ncx_getn_short_uchar(const void **xpp, size_t nelems, uchar *ip); extern int ncx_getn_short_short(const void **xpp, size_t nelems, short *ip); extern int ncx_getn_short_int(const void **xpp, size_t nelems, int *ip); extern int ncx_getn_short_long(const void **xpp, size_t nelems, long *ip); extern int ncx_getn_short_float(const void **xpp, size_t nelems, float *ip); extern int ncx_getn_short_double(const void **xpp, size_t nelems, double *ip); extern int ncx_pad_getn_short_schar(const void **xpp, size_t nelems, schar *ip); extern int ncx_pad_getn_short_uchar(const void **xpp, size_t nelems, uchar *ip); extern int ncx_pad_getn_short_short(const void **xpp, size_t nelems, short *ip); extern int ncx_pad_getn_short_int(const void **xpp, size_t nelems, int *ip); extern int ncx_pad_getn_short_long(const void **xpp, size_t nelems, long *ip); extern int ncx_pad_getn_short_float(const void **xpp, size_t nelems, float *ip); extern int ncx_pad_getn_short_double(const void **xpp, size_t nelems, double *ip); extern int ncx_putn_short_schar(void **xpp, size_t nelems, const schar *ip); extern int ncx_putn_short_uchar(void **xpp, size_t nelems, const uchar *ip); extern int ncx_putn_short_short(void **xpp, size_t nelems, const short *ip); extern int ncx_putn_short_int(void **xpp, size_t nelems, const int *ip); extern int ncx_putn_short_long(void **xpp, size_t nelems, const long *ip); extern int ncx_putn_short_float(void **xpp, size_t nelems, const float *ip); extern int ncx_putn_short_double(void **xpp, size_t nelems, const double *ip); extern int ncx_pad_putn_short_schar(void **xpp, size_t nelems, const schar *ip); extern int ncx_pad_putn_short_uchar(void **xpp, size_t nelems, const uchar *ip); extern int ncx_pad_putn_short_short(void **xpp, size_t nelems, const short *ip); extern int ncx_pad_putn_short_int(void **xpp, size_t nelems, const int *ip); extern int ncx_pad_putn_short_long(void **xpp, size_t nelems, const long *ip); extern int ncx_pad_putn_short_float(void **xpp, size_t nelems, const float *ip); extern int ncx_pad_putn_short_double(void **xpp, size_t nelems, const double *ip); extern int ncx_getn_int_schar(const void **xpp, size_t nelems, schar *ip); extern int ncx_getn_int_uchar(const void **xpp, size_t nelems, uchar *ip); extern int ncx_getn_int_short(const void **xpp, size_t nelems, short *ip); extern int ncx_getn_int_int(const void **xpp, size_t nelems, int *ip); extern int ncx_getn_int_long(const void **xpp, size_t nelems, long *ip); extern int ncx_getn_int_float(const void **xpp, size_t nelems, float *ip); extern int ncx_getn_int_double(const void **xpp, size_t nelems, double *ip); extern int ncx_putn_int_schar(void **xpp, size_t nelems, const schar *ip); extern int ncx_putn_int_uchar(void **xpp, size_t nelems, const uchar *ip); extern int ncx_putn_int_short(void **xpp, size_t nelems, const short *ip); extern int ncx_putn_int_int(void **xpp, size_t nelems, const int *ip); extern int ncx_putn_int_long(void **xpp, size_t nelems, const long *ip); extern int ncx_putn_int_float(void **xpp, size_t nelems, const float *ip); extern int ncx_putn_int_double(void **xpp, size_t nelems, const double *ip); extern int ncx_getn_float_schar(const void **xpp, size_t nelems, schar *ip); extern int ncx_getn_float_uchar(const void **xpp, size_t nelems, uchar *ip); extern int ncx_getn_float_short(const void **xpp, size_t nelems, short *ip); extern int ncx_getn_float_int(const void **xpp, size_t nelems, int *ip); extern int ncx_getn_float_long(const void **xpp, size_t nelems, long *ip); extern int ncx_getn_float_float(const void **xpp, size_t nelems, float *ip); extern int ncx_getn_float_double(const void **xpp, size_t nelems, double *ip); extern int ncx_putn_float_schar(void **xpp, size_t nelems, const schar *ip); extern int ncx_putn_float_uchar(void **xpp, size_t nelems, const uchar *ip); extern int ncx_putn_float_short(void **xpp, size_t nelems, const short *ip); extern int ncx_putn_float_int(void **xpp, size_t nelems, const int *ip); extern int ncx_putn_float_long(void **xpp, size_t nelems, const long *ip); extern int ncx_putn_float_float(void **xpp, size_t nelems, const float *ip); extern int ncx_putn_float_double(void **xpp, size_t nelems, const double *ip); extern int ncx_getn_double_schar(const void **xpp, size_t nelems, schar *ip); extern int ncx_getn_double_uchar(const void **xpp, size_t nelems, uchar *ip); extern int ncx_getn_double_short(const void **xpp, size_t nelems, short *ip); extern int ncx_getn_double_int(const void **xpp, size_t nelems, int *ip); extern int ncx_getn_double_long(const void **xpp, size_t nelems, long *ip); extern int ncx_getn_double_float(const void **xpp, size_t nelems, float *ip); extern int ncx_getn_double_double(const void **xpp, size_t nelems, double *ip); extern int ncx_putn_double_schar(void **xpp, size_t nelems, const schar *ip); extern int ncx_putn_double_uchar(void **xpp, size_t nelems, const uchar *ip); extern int ncx_putn_double_short(void **xpp, size_t nelems, const short *ip); extern int ncx_putn_double_int(void **xpp, size_t nelems, const int *ip); extern int ncx_putn_double_long(void **xpp, size_t nelems, const long *ip); extern int ncx_putn_double_float(void **xpp, size_t nelems, const float *ip); extern int ncx_putn_double_double(void **xpp, size_t nelems, const double *ip); /* * Other aggregate conversion functions. */ /* read ASCII characters */ extern int ncx_getn_text(const void **xpp, size_t nchars, char *cp); extern int ncx_pad_getn_text(const void **xpp, size_t nchars, char *cp); /* write ASCII characters */ extern int ncx_putn_text(void **xpp, size_t nchars, const char *cp); extern int ncx_pad_putn_text(void **xpp, size_t nchars, const char *cp); /* for symmetry */ #define ncx_getn_char_char(xpp, nelems, fillp) ncx_getn_text(xpp, nelems, fillp) #define ncx_putn_char_char(xpp, nelems, fillp) ncx_putn_text(xpp, nelems, fillp) /* read opaque data */ extern int ncx_getn_void(const void **xpp, size_t nchars, void *vp); extern int ncx_pad_getn_void(const void **xpp, size_t nchars, void *vp); /* write opaque data */ extern int ncx_putn_void(void **xpp, size_t nchars, const void *vp); extern int ncx_pad_putn_void(void **xpp, size_t nchars, const void *vp); #endif /* _NCX_H_ */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/v2i.c0000644000175000017500000005176611606020250021343 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: v2i.c,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #include "ncconfig.h" #include #ifndef NO_SYS_TYPES_H # include /* Keep before netcdf.h or Win64 gets confused. */ #endif /* NO_SYS_TYPES_H */ #include "netcdf.h" #ifndef NO_NETCDF_2 #if SIZEOF_LONG == SIZEOF_SIZE_T /* * We don't have to copy the arguments to switch from 'long' * to 'size_t' or 'ptrdiff_t'. Use dummy macros. */ # define NDIMS_DECL # define A_DECL(name, type, ndims, rhs) \ const type *const name = ((const type *)(rhs)) # define A_FREE(name) # define A_INIT(lhs, type, ndims, rhs) #else /* * We do have to copy the arguments to switch from 'long' * to 'size_t' or 'ptrdiff_t'. In my tests on an SGI, * any additional cost was lost in measurement variation. */ # include "onstack.h" # include "nc.h" static size_t nvdims(int ncid, int varid) { NC *ncp; if(NC_check_id(ncid, &ncp) != NC_NOERR) return 0; { const NC_var *const varp = NC_lookupvar(ncp, varid); if(varp == NULL) return 0; return varp->ndims; } } #define NDIMS_DECL const size_t ndims = nvdims(ncid, varid); # define A_DECL(name, type, ndims, rhs) \ ALLOC_ONSTACK(name, type, ndims) # define A_FREE(name) \ FREE_ONSTACK(name) # define A_INIT(lhs, type, ndims, rhs) \ { \ const long *lp = rhs; \ type *tp = lhs; \ type *const end = lhs + ndims; \ while(tp < end) \ { \ *tp++ = (type) *lp++; \ } \ } #endif typedef signed char schar; /* * Computes number of record variables in an open netCDF file, and an array of * the record variable ids, if the array parameter is non-null. */ static int numrecvars(int ncid, int *nrecvarsp, int *recvarids) { int status; int nvars = 0; int ndims = 0; int nrecvars; int varid; int recdimid; int dimids[MAX_NC_DIMS]; status = nc_inq_nvars(ncid, &nvars); if(status != NC_NOERR) return status; status = nc_inq_unlimdim(ncid, &recdimid); if(status != NC_NOERR) return status; if (recdimid == -1) { *nrecvarsp = 0; return NC_NOERR; } nrecvars = 0; for (varid = 0; varid < nvars; varid++) { status = nc_inq_varndims(ncid, varid, &ndims); if(status != NC_NOERR) return status; status = nc_inq_vardimid(ncid, varid, dimids); if(status != NC_NOERR) return status; if (ndims > 0 && dimids[0] == recdimid) { if (recvarids != NULL) recvarids[nrecvars] = varid; nrecvars++; } } *nrecvarsp = nrecvars; return NC_NOERR; } /* * Computes record size (in bytes) of the record variable with a specified * variable id. Returns size as 0 if not a record variable. */ static int ncrecsize(int ncid, int varid, size_t *recsizep) { int status; int recdimid; nc_type type; int ndims; int dimids[MAX_NC_DIMS]; int id; size_t size; *recsizep = 0; status = nc_inq_unlimdim(ncid, &recdimid); if(status != NC_NOERR) return status; status = nc_inq_vartype(ncid, varid, &type); if(status != NC_NOERR) return status; status = nc_inq_varndims(ncid, varid, &ndims); if(status != NC_NOERR) return status; status = nc_inq_vardimid(ncid, varid, dimids); if(status != NC_NOERR) return status; if (ndims == 0 || dimids[0] != recdimid) { return NC_NOERR; } size = nctypelen(type); for (id = 1; id < ndims; id++) { size_t len; status = nc_inq_dimlen(ncid, dimids[id], &len); if(status != NC_NOERR) return status; size *= len; } *recsizep = size; return NC_NOERR; } /* * Retrieves the dimension sizes of a variable with a specified variable id in * an open netCDF file. Returns -1 on error. */ static int dimsizes(int ncid, int varid, size_t *sizes) { int status; int ndims; int id; int dimids[MAX_NC_DIMS]; status = nc_inq_varndims(ncid, varid, &ndims); if(status != NC_NOERR) return status; status = nc_inq_vardimid(ncid, varid, dimids); if(status != NC_NOERR) return status; if (ndims == 0 || sizes == NULL) return NC_NOERR; for (id = 0; id < ndims; id++) { size_t len; status = nc_inq_dimlen(ncid, dimids[id], &len); if(status != NC_NOERR) return status; sizes[id] = len; } return NC_NOERR; } /* * Retrieves the number of record variables, the record variable ids, and the * record size of each record variable. If any pointer to info to be returned * is null, the associated information is not returned. Returns -1 on error. */ int nc_inq_rec( int ncid, size_t *nrecvarsp, int *recvarids, size_t *recsizes) { int status; int nvars = 0; int recdimid; int varid; int rvarids[MAX_NC_VARS]; int nrvars = 0; status = nc_inq_nvars(ncid, &nvars); if(status != NC_NOERR) return status; status = nc_inq_unlimdim(ncid, &recdimid); if(status != NC_NOERR) return status; *nrecvarsp = 0; if (recdimid == -1) return NC_NOERR; status = numrecvars(ncid, &nrvars, rvarids); if(status != NC_NOERR) return status; if (nrecvarsp != NULL) *nrecvarsp = nrvars; if (recvarids != NULL) for (varid = 0; varid < nrvars; varid++) recvarids[varid] = rvarids[varid]; if (recsizes != NULL) for (varid = 0; varid < nrvars; varid++) { size_t rsize; status = ncrecsize(ncid, rvarids[varid], &rsize); if (status != NC_NOERR) return status; recsizes[varid] = rsize; } return NC_NOERR; } /* * Write one record's worth of data, except don't write to variables for which * the address of the data to be written is NULL. Return -1 on error. This is * the same as the ncrecput() in the library, except that can handle errors * better. */ int nc_put_rec( int ncid, size_t recnum, void* const* datap) { int status; int varid; int rvarids[MAX_NC_VARS]; int nrvars; size_t start[MAX_NC_DIMS]; size_t edges[MAX_NC_DIMS]; status = numrecvars(ncid, &nrvars, rvarids); if(status != NC_NOERR) return status; if (nrvars == 0) return NC_NOERR; start[0] = recnum; for (varid = 1; varid < nrvars; varid++) start[varid] = 0; for (varid = 0; varid < nrvars; varid++) { if (datap[varid] != NULL) { status = dimsizes(ncid, rvarids[varid], edges); if(status != NC_NOERR) return status; edges[0] = 1; /* only 1 record's worth */ status = nc_put_vara(ncid, rvarids[varid], start, edges, datap[varid]); if(status != NC_NOERR) return status; } } return 0; } /* * Read one record's worth of data, except don't read from variables for which * the address of the data to be read is null. Return -1 on error. This is * the same as the ncrecget() in the library, except that can handle errors * better. */ int nc_get_rec( int ncid, size_t recnum, void **datap) { int status; int varid; int rvarids[MAX_NC_VARS]; int nrvars; size_t start[MAX_NC_DIMS]; size_t edges[MAX_NC_DIMS]; status = numrecvars(ncid, &nrvars, rvarids); if(status != NC_NOERR) return status; if (nrvars == 0) return NC_NOERR; start[0] = recnum; for (varid = 1; varid < nrvars; varid++) start[varid] = 0; for (varid = 0; varid < nrvars; varid++) { if (datap[varid] != NULL) { status = dimsizes(ncid, rvarids[varid], edges); if(status != NC_NOERR) return status; edges[0] = 1; /* only 1 record's worth */ status = nc_get_vara(ncid, rvarids[varid], start, edges, datap[varid]); if(status != NC_NOERR) return status; } } return 0; } /* Begin globals */ /* * Error code */ int ncerr = NC_NOERR ; /* * The subroutines in error.c emit no messages unless NC_VERBOSE bit is on. * They call exit() when NC_FATAL bit is on. */ int ncopts = (NC_FATAL | NC_VERBOSE) ; /* End globals */ /* Begin error handling */ #include #include #include /* */ void nc_advise(const char *routine_name, int err, const char *fmt,...) { va_list args; if(NC_ISSYSERR(err)) ncerr = NC_SYSERR; else ncerr = err; if( ncopts & NC_VERBOSE ) { (void) fprintf(stderr,"%s: ", routine_name); va_start(args ,fmt); (void) vfprintf(stderr,fmt,args); va_end(args); if(err != NC_NOERR) { (void) fprintf(stderr,": %s", nc_strerror(err)); } (void) fputc('\n',stderr); (void) fflush(stderr); /* to ensure log files are current */ } if( (ncopts & NC_FATAL) && err != NC_NOERR ) { exit(ncopts); } } /* End error handling */ int nccreate(const char* path, int cmode) { int ncid; const int status = nc_create(path, cmode, &ncid); if(status != NC_NOERR) { nc_advise("nccreate", status, "filename \"%s\"", path); return -1; } return ncid; } int ncopen(const char *path, int mode) { int ncid; const int status = nc_open(path, mode, &ncid); if(status != NC_NOERR) { nc_advise("ncopen", status, "filename \"%s\"", path); return -1; } return ncid; } int ncredef(int ncid) { const int status = nc_redef(ncid); if(status != NC_NOERR) { nc_advise("ncredef", status, "ncid %d", ncid); return -1; } return 0; } int ncendef(int ncid) { const int status = nc_enddef(ncid); if(status != NC_NOERR) { nc_advise("ncendef", status, "ncid %d", ncid); return -1; } return 0; } int ncclose(int ncid) { const int status = nc_close(ncid); if(status != NC_NOERR) { nc_advise("ncclose", status, "ncid %d", ncid); return -1; } return 0; } int ncinquire( int ncid, int* ndims, int* nvars, int* natts, int* recdim ) { int nd, nv, na; const int status = nc_inq(ncid, &nd, &nv, &na, recdim); if(status != NC_NOERR) { nc_advise("ncinquire", status, "ncid %d", ncid); return -1; } /* else */ if(ndims != NULL) *ndims = (int) nd; if(nvars != NULL) *nvars = (int) nv; if(natts != NULL) *natts = (int) na; return ncid; } int ncsync(int ncid) { const int status = nc_sync(ncid); if(status != NC_NOERR) { nc_advise("ncsync", status, "ncid %d", ncid); return -1; } return 0; } int ncabort(int ncid) { const int status = nc_abort(ncid); if(status != NC_NOERR) { nc_advise("ncabort", status, "ncid %d", ncid); return -1; } return 0; } int ncdimdef( int ncid, const char* name, long length ) { int dimid; int status; if(length < 0) { status = NC_EDIMSIZE; nc_advise("ncdimdef", status, "ncid %d", ncid); return -1; } status = nc_def_dim(ncid, name, (size_t)length, &dimid); if(status != NC_NOERR) { nc_advise("ncdimdef", status, "ncid %d", ncid); return -1; } return dimid; } int ncdimid(int ncid, const char* name) { int dimid; const int status = nc_inq_dimid(ncid, name, &dimid); if(status != NC_NOERR) { nc_advise("ncdimid", status, "ncid %d", ncid); return -1; } return dimid; } int ncdiminq( int ncid, int dimid, char* name, long* length ) { size_t ll; const int status = nc_inq_dim(ncid, dimid, name, &ll); if(status != NC_NOERR) { nc_advise("ncdiminq", status, "ncid %d", ncid); return -1; } /* else */ if(length != NULL) *length = (int) ll; return dimid; } int ncdimrename( int ncid, int dimid, const char* name ) { const int status = nc_rename_dim(ncid, dimid, name); if(status != NC_NOERR) { nc_advise("ncdimrename", status, "ncid %d", ncid); return -1; } return dimid; } int ncvardef( int ncid, const char* name, nc_type datatype, int ndims, const int* dim ) { int varid = -1; const int status = nc_def_var(ncid, name, datatype, ndims, dim, &varid); if(status != NC_NOERR) { nc_advise("ncvardef", status, "ncid %d", ncid); return -1; } return varid; } int ncvarid( int ncid, const char* name ) { int varid = -1; const int status = nc_inq_varid(ncid, name, &varid); if(status != NC_NOERR) { nc_advise("ncvarid", status, "ncid %d", ncid); return -1; } return varid; } int ncvarinq( int ncid, int varid, char* name, nc_type* datatype, int* ndims, int* dim, int* natts ) { int nd, na; const int status = nc_inq_var(ncid, varid, name, datatype, &nd, dim, &na); if(status != NC_NOERR) { nc_advise("ncvarinq", status, "ncid %d", ncid); return -1; } /* else */ if(ndims != NULL) *ndims = (int) nd; if(natts != NULL) *natts = (int) na; return varid; } int ncvarput1( int ncid, int varid, const long* index, const void* value ) { NDIMS_DECL A_DECL(coordp, size_t, ndims, index); A_INIT(coordp, size_t, ndims, index); { const int status = nc_put_var1(ncid, varid, coordp, value); A_FREE(coordp); if(status != NC_NOERR) { nc_advise("ncvarput1", status, "ncid %d", ncid); return -1; } } return 0; } int ncvarget1( int ncid, int varid, const long* index, void* value ) { NDIMS_DECL A_DECL(coordp, size_t, ndims, index); A_INIT(coordp, size_t, ndims, index); { const int status = nc_get_var1(ncid, varid, coordp, value); A_FREE(coordp); if(status != NC_NOERR) { nc_advise("ncdimid", status, "ncid %d", ncid); return -1; } } return 0; } int ncvarput( int ncid, int varid, const long* start, const long* count, const void* value ) { NDIMS_DECL A_DECL(stp, size_t, ndims, start); A_DECL(cntp, size_t, ndims, count); A_INIT(stp, size_t, ndims, start); A_INIT(cntp, size_t, ndims, count); { const int status = nc_put_vara(ncid, varid, stp, cntp, value); A_FREE(cntp); A_FREE(stp); if(status != NC_NOERR) { nc_advise("ncvarput", status, "ncid %d", ncid); return -1; } } return 0; } int ncvarget( int ncid, int varid, const long* start, const long* count, void* value ) { NDIMS_DECL A_DECL(stp, size_t, ndims, start); A_DECL(cntp, size_t, ndims, count); A_INIT(stp, size_t, ndims, start); A_INIT(cntp, size_t, ndims, count); { const int status = nc_get_vara(ncid, varid, stp, cntp, value); A_FREE(cntp); A_FREE(stp); if(status != NC_NOERR) { nc_advise("ncvarget", status, "ncid %d; varid %d", ncid, varid); return -1; } } return 0; } int ncvarputs( int ncid, int varid, const long* start, const long* count, const long* stride, const void* value ) { if(stride == NULL) return ncvarput(ncid, varid, start, count, value); /* else */ { NDIMS_DECL A_DECL(stp, size_t, ndims, start); A_DECL(cntp, size_t, ndims, count); A_DECL(strdp, ptrdiff_t, ndims, stride); A_INIT(stp, size_t, ndims, start); A_INIT(cntp, size_t, ndims, count); A_INIT(strdp, ptrdiff_t, ndims, stride); { const int status = nc_put_vars(ncid, varid, stp, cntp, strdp, value); A_FREE(strdp); A_FREE(cntp); A_FREE(stp); if(status != NC_NOERR) { nc_advise("ncvarputs", status, "ncid %d", ncid); return -1; } } return 0; } } int ncvargets( int ncid, int varid, const long* start, const long* count, const long* stride, void* value ) { if(stride == NULL) return ncvarget(ncid, varid, start, count, value); /* else */ { NDIMS_DECL A_DECL(stp, size_t, ndims, start); A_DECL(cntp, size_t, ndims, count); A_DECL(strdp, ptrdiff_t, ndims, stride); A_INIT(stp, size_t, ndims, start); A_INIT(cntp, size_t, ndims, count); A_INIT(strdp, ptrdiff_t, ndims, stride); { const int status = nc_get_vars(ncid, varid, stp, cntp, strdp, value); A_FREE(strdp); A_FREE(cntp); A_FREE(stp); if(status != NC_NOERR) { nc_advise("ncvargets", status, "ncid %d", ncid); return -1; } } return 0; } } int ncvarputg( int ncid, int varid, const long* start, const long* count, const long* stride, const long* map, const void* value ) { if(map == NULL) return ncvarputs(ncid, varid, start, count, stride, value); /* else */ { NDIMS_DECL A_DECL(stp, size_t, ndims, start); A_DECL(cntp, size_t, ndims, count); A_DECL(strdp, ptrdiff_t, ndims, stride); A_DECL(imp, ptrdiff_t, ndims, map); A_INIT(stp, size_t, ndims, start); A_INIT(cntp, size_t, ndims, count); A_INIT(strdp, ptrdiff_t, ndims, stride); A_INIT(imp, ptrdiff_t, ndims, map); { const int status = nc_put_varm(ncid, varid, stp, cntp, strdp, imp, value); A_FREE(imp); A_FREE(strdp); A_FREE(cntp); A_FREE(stp); if(status != NC_NOERR) { nc_advise("ncvarputg", status, "ncid %d", ncid); return -1; } } return 0; } } int ncvargetg( int ncid, int varid, const long* start, const long* count, const long* stride, const long* map, void* value ) { if(map == NULL) return ncvargets(ncid, varid, start, count, stride, value); /* else */ { NDIMS_DECL A_DECL(stp, size_t, ndims, start); A_DECL(cntp, size_t, ndims, count); A_DECL(strdp, ptrdiff_t, ndims, stride); A_DECL(imp, ptrdiff_t, ndims, map); A_INIT(stp, size_t, ndims, start); A_INIT(cntp, size_t, ndims, count); A_INIT(strdp, ptrdiff_t, ndims, stride); A_INIT(imp, ptrdiff_t, ndims, map); { const int status = nc_get_varm(ncid, varid, stp, cntp, strdp, imp, value); A_FREE(imp); A_FREE(strdp); A_FREE(cntp); A_FREE(stp); if(status != NC_NOERR) { nc_advise("ncvargetg", status, "ncid %d", ncid); return -1; } } return 0; } } int ncvarrename( int ncid, int varid, const char* name ) { const int status = nc_rename_var(ncid, varid, name); if(status != NC_NOERR) { nc_advise("ncvarrename", status, "ncid %d", ncid); return -1; } return varid; } int ncattput( int ncid, int varid, const char* name, nc_type datatype, int len, const void* value ) { const int status = nc_put_att(ncid, varid, name, datatype, len, value); if(status != NC_NOERR) { nc_advise("ncattput", status, "ncid %d", ncid); return -1; } return 0; } int ncattinq( int ncid, int varid, const char* name, nc_type* datatype, int* len ) { size_t ll; const int status = nc_inq_att(ncid, varid, name, datatype, &ll); if(status != NC_NOERR) { nc_advise("ncattinq", status, "ncid %d; varid %d; attname \"%s\"", ncid, varid, name); return -1; } if(len != NULL) *len = (int) ll; return 1; } int ncattget( int ncid, int varid, const char* name, void* value ) { const int status = nc_get_att(ncid, varid, name, value); if(status != NC_NOERR) { nc_advise("ncattget", status, "ncid %d", ncid); return -1; } return 1; } int ncattcopy( int ncid_in, int varid_in, const char* name, int ncid_out, int varid_out ) { const int status = nc_copy_att(ncid_in, varid_in, name, ncid_out, varid_out); if(status != NC_NOERR) { nc_advise("ncattcopy", status, "%s", name); return -1; } return 0; } int ncattname( int ncid, int varid, int attnum, char* name ) { const int status = nc_inq_attname(ncid, varid, attnum, name); if(status != NC_NOERR) { nc_advise("ncattname", status, "ncid %d", ncid); return -1; } return attnum; } int ncattrename( int ncid, int varid, const char* name, const char* newname ) { const int status = nc_rename_att(ncid, varid, name, newname); if(status != NC_NOERR) { nc_advise("ncattrename", status, "ncid %d", ncid); return -1; } return 1; } int ncattdel( int ncid, int varid, const char* name ) { const int status = nc_del_att(ncid, varid, name); if(status != NC_NOERR) { nc_advise("ncattdel", status, "ncid %d", ncid); return -1; } return 1; } #endif /* NO_NETCDF_2 */ #ifndef NO_NETCDF_2 int ncsetfill( int ncid, int fillmode ) { int oldmode = -1; const int status = nc_set_fill(ncid, fillmode, &oldmode); if(status != NC_NOERR) { nc_advise("ncsetfill", status, "ncid %d", ncid); return -1; } return oldmode; } int ncrecinq( int ncid, int* nrecvars, int* recvarids, long* recsizes ) { size_t nrv = 0; size_t rs[NC_MAX_VARS]; /* TODO */ const int status = nc_inq_rec(ncid, &nrv, recvarids, rs); if(status != NC_NOERR) { nc_advise("ncrecinq", status, "ncid %d", ncid); return -1; } if(nrecvars != NULL) *nrecvars = (int) nrv; if(recsizes != NULL) { size_t ii; for(ii = 0; ii < nrv; ii++) { recsizes[ii] = (long) rs[ii]; } } return (int) nrv; } int ncrecget( int ncid, long recnum, void** datap ) { const int status = nc_get_rec(ncid, (size_t)recnum, datap); if(status != NC_NOERR) { nc_advise("ncrecget", status, "ncid %d", ncid); return -1; } return 0; } int ncrecput( int ncid, long recnum, void* const* datap ) { const int status = nc_put_rec(ncid, (size_t)recnum, datap); if(status != NC_NOERR) { nc_advise("ncrecput", status, "ncid %d", ncid); return -1; } return 0; } #endif /* NO_NETCDF_2 */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/netcdf.30000644000175000017500000013605011606020250022014 0ustar amckinstryamckinstry.nr yr \n(yr+1900 .af mo 01 .af dy 01 .TH NETCDF 3 "1997-04-18" "Printed: \n(yr-\n(mo-\n(dy" "UNIDATA LIBRARY FUNCTIONS" .SH NAME netcdf \- Unidata Network Common Data Form (netCDF) library, version 3 interface .SH SYNOPSIS .ft B .na .nh #include "netcdf.h" .sp cc ... -lnetcdf .ad .hy .SH "LIBRARY VERSION" .LP This document describes version 3 of Unidata netCDF data-access interface for the C programming language. .HP \fBconst char* nc_inq_libvers()\fR .sp Returns a string identifying the version of the netCDF library, and when it was built, like: "3.1a of Aug 22 1996 12:57:47 $". .LP The RCS \fBident(1)\fP command will find a string like "$\|Id: @\|(#) netcdf library version 3.1a of Sep 6 1996 15:56:26 $" in the library. The SCCS \fBwhat(1)\fP command will find a string like "netcdf library version 3.1a of Aug 23 1996 16:07:40 $". .SH "RETURN VALUES" .LP All netCDF functions (except \fBnc_inq_libvers(\|)\fR and \fBnc_strerror(\|)\fR) return an integer status. This behavior replaces the \fBncerr()\fR function used in previous versions of the library. If this returned status value is not equal to \fBNC_NOERR\fR (zero), it indicates that an error occurred. The possible status values are defined in system include file and in "netcdf.h". .HP \fBconst char* nc_strerror(int \fIstatus\fP)\fR .sp Returns a string textual translation of the \fIstatus\fP value, like "Attribute or variable name contains illegal characters" or "No such file or directory". .HP \fBint nc_create(const char \fIpath\fP[], int \fIcmode\fP, int* \fIncid\fP)\fR .sp (Corresponds to \fBnccreate(\|)\fR in version 2) .sp Creates a new netCDF dataset at \fIpath\fP, returning a netCDF ID in \fIncid\fP. The argument \fIcmode\fP may include the bitwise-or of the following flags: \fBNC_NOCLOBBER\fR to protect existing datasets (default silently blows them away), \fBNC_SHARE\fR for synchronous dataset updates (default is to buffer accesses), and \fBNC_LOCK\fR (not yet implemented). When a netCDF dataset is created, is is opened \fBNC_WRITE\fR. The new netCDF dataset is in define mode. \fBNC_64BIT_OFFSET\fR. to create a file in the 64-bit offset (as opposed to classic , the default). 64-bit offset allows the creation of very large files with far fewer restrictions than netCDF classic , but can only be read by the netCDF library version 3.6 or greater. Users are cautioned that files that use the 64-bit offset will not be recognized by netCDF applications linked to an earlier version of the netCDF library than 3.6. Applications linked to version 3.6 or later will be able to transparently access either the classic or 64-bit offset . .HP \fBint nc__create(const char \fIpath\fP[], int \fIcmode\fP, size_t \fIinitialsize\fP, size_t* \fIchunksize\fP, int* \fIncid\fP)\fR .sp Like \fBnc_create(\|)\fR but has additional performance tuning parameters. .sp The argument \fIinitialsize\fP sets the initial size of the file at creation time. .sp See \fBnc__open(\|)\fR below for an explanation of the \fIchunksize\fP parameter. .HP \fBint nc_open(const char \fIpath\fP[], int \fImode\fP, int* \fIncid\fP)\fR .sp (Corresponds to \fBncopen(\|)\fR in version 2) .sp Opens a existing netCDF dataset at \fIpath\fP returning a netCDF ID in \fIncid\fP. The type of access is described by the \fImode\fP parameter, which may include the bitwise-or of the following flags: \fBNC_WRITE\fR for read-write access (default read-only), \fBNC_SHARE\fR for synchronous dataset updates (default is to buffer accesses), and \fBNC_LOCK\fR (not yet implemented). .HP \fBint nc__open(const char \fIpath\fP[], int \fImode\fP, size_t* \fIchunksize\fP, int* \fIncid\fP)\fR .sp Like \fBnc_open(\|)\fR but has an additional performance tuning parameter. .sp The argument referenced by \fIchunksize\fP controls a space versus time tradeoff, memory allocated in the netcdf library versus number of system calls. Because of internal requirements, the value may not be set to exactly the value requested. The actual value chosen is returned by reference. Using the value \fBNC_SIZEHINT_DEFAULT\fR causes the library to choose a default. How the system choses the default depends on the system. On many systems, the "preferred I/O block size" is available from the \fBstat()\fR system call, \fBstruct stat\fR member \fBst_blksize\fR. If this is available it is used. Lacking that, twice the system pagesize is used. Lacking a call to discover the system pagesize, we just set default chunksize to 8192. .sp The chunksize is a property of a given open netcdf descriptor \fIncid\fP, it is not a persistent property of the netcdf dataset. .HP \fBint nc_redef(int \fIncid\fP)\fR .sp (Corresponds to \fBncredef(\|)\fR in version 2) .sp Puts an open netCDF dataset into define mode, so dimensions, variables, and attributes can be added or renamed and attributes can be deleted. .HP \fBint nc_enddef(int \fIncid\fP)\fR .sp (Corresponds to \fBncendef(\|)\fR in version 2) .sp Takes an open netCDF dataset out of define mode. The changes made to the netCDF dataset while it was in define mode are checked and committed to disk if no problems occurred. Some data values may be written as well, see "VARIABLE PREFILLING" below. After a successful call, variable data can be read or written to the dataset. .HP \fBint nc__enddef(int \fIncid\fP, size_t \fIh_minfree\fP, size_t \fIv_align\fP, size_t \fIv_minfree\fP, size_t \fIr_align\fP)\fR .sp Like \fBnc_enddef(\|)\fR but has additional performance tuning parameters. .sp Caution: this function exposes internals of the netcdf version 1 file format. It may not be available on future netcdf implementations. .sp The current netcdf file format has three sections, the "header" section, the data section for fixed size variables, and the data section for variables which have an unlimited dimension (record variables). The header begins at the beginning of the file. The index (offset) of the beginning of the other two sections is contained in the header. Typically, there is no space between the sections. This causes copying overhead to accrue if one wishes to change the size of the sections, as may happen when changing names of things, text attribute values, adding attributes or adding variables. Also, for buffered i/o, there may be advantages to aligning sections in certain ways. .sp The minfree parameters allow one to control costs of future calls to \fBnc_redef(\|)\fR, \fBnc_enddef(\|)\fR by requesting that \fIminfree\fP bytes be available at the end of the section. The \fIh_minfree\fP parameter sets the pad at the end of the "header" section. The \fIv_minfree\fP parameter sets the pad at the end of the data section for fixed size variables. .sp The align parameters allow one to set the alignment of the beginning of the corresponding sections. The beginning of the section is rounded up to an index which is a multiple of the align parameter. The flag value \fBNC_ALIGN_CHUNK\fR tells the library to use the chunksize (see above) as the align parameter. The \fIv_align\fP parameter controls the alignment of the beginning of the data section for fixed size variables. The \fIr_align\fP parameter controls the alignment of the beginning of the data section for variables which have an unlimited dimension (record variables). .sp The file format requires mod 4 alignment, so the align parameters are silently rounded up to multiples of 4. The usual call, \fBnc_enddef(\fIncid\fP)\fR is equivalent to \fBnc__enddef(\fIncid\fP, 0, 4, 0, 4)\fR. .sp The file format does not contain a "record size" value, this is calculated from the sizes of the record variables. This unfortunate fact prevents us from providing minfree and alignment control of the "records" in a netcdf file. If you add a variable which has an unlimited dimension, the third section will always be copied with the new variable added. .HP \fBint nc_sync(int \fIncid\fP)\fR .sp (Corresponds to \fBncsync(\|)\fR in version 2) .sp Unless the \fBNC_SHARE\fR bit is set in \fBnc_open(\|)\fR or \fBnc_create(\|)\fR, accesses to the underlying netCDF dataset are buffered by the library. This function synchronizes the state of the underlying dataset and the library. This is done automatically by \fBnc_close(\|)\fR and \fBnc_enddef(\|)\fR. .HP \fBint nc_abort(int \fIncid\fP)\fR .sp (Corresponds to \fBncabort(\|)\fR in version 2) .sp You don't need to call this function. This function is called automatically by \fBnc_close(\|)\fR if the netCDF was in define mode and something goes wrong with the commit. If the netCDF dataset isn't in define mode, then this function is equivalent to \fBnc_close(\|)\fR. If it is called after \fBnc_redef(\|)\fR, but before \fBnc_enddef(\|)\fR, the new definitions are not committed and the dataset is closed. If it is called after \fBnc_create(\|)\fR but before \fBnc_enddef(\|)\fR, the dataset disappears. .HP \fBint nc_close(int \fIncid\fP)\fR .sp (Corresponds to \fBncclose(\|)\fR in version 2) .sp Closes an open netCDF dataset. If the dataset is in define mode, \fBnc_enddef(\|)\fR will be called before closing. After a dataset is closed, its ID may be reassigned to another dataset. .HP \fBint nc_inq(int \fIncid\fP, int* \fIndims\fP, int* \fInvars\fP, int* \fInatts\fP, int* \fIunlimdimid\fP)\fR .HP \fBint nc_inq_ndims(int \fIncid\fP, int* \fIndims\fP)\fR .HP \fBint nc_inq_nvars(int \fIncid\fP, int* \fInvars\fP)\fR .HP \fBint nc_inq_natts(int \fIncid\fP, int* \fInatts\fP)\fR .HP \fBint nc_inq_unlimdim(int \fIncid\fP, int* \fIunlimdimid\fP)\fR .HP \fBint nc_inq_format(int \fIncid\fP, int* \fIformatn\fP)\fR .sp (Replace \fBncinquire(\|)\fR in version 2) .sp Use these functions to find out what is in a netCDF dataset. Upon successful return, \fIndims\fP will contain the number of dimensions defined for this netCDF dataset, \fInvars\fP will contain the number of variables, \fInatts\fP will contain the number of attributes, and \fIunlimdimid\fP will contain the dimension ID of the unlimited dimension if one exists, or -1 otherwise. \fIformatn\fP will contain the version number of the dataset <>, one of \fBNC_FORMAT_CLASSIC\fR, \fBNC_FORMAT_64BIT\fR, \fBNC_FORMAT_NETCDF4\fR, or \fBNC_FORMAT_NETCDF4_CLASSIC\fR. If any of the return parameters is a \fBNULL\fR pointer, then the corresponding information will not be returned; hence, no space need be allocated for it. .HP \fBint nc_def_dim(int \fIncid\fP, const char \fIname\fP[], size_t \fIlen\fP, int* \fIdimid\fP)\fR .sp (Corresponds to \fBncdimdef(\|)\fR in version 2) .sp Adds a new dimension to an open netCDF dataset, which must be in define mode. \fIname\fP is the dimension name. If \fIdimid\fP is not a \fBNULL\fR pointer then upon successful completion \fIdimid\fP will contain the dimension ID of the newly created dimension. .HP \fBint nc_inq_dimid(int \fIncid\fP, const char \fIname\fP[], int* \fIdimid\fP)\fR .sp (Corresponds to \fBncdimid(\|)\fR in version 2) .sp Given a dimension name, returns the ID of a netCDF dimension in \fIdimid\fP. .HP \fBint nc_inq_dim(int \fIncid\fP, int \fIdimid\fP, char \fIname\fP[], size_t* \fIlen\fP)\fR .HP \fBint nc_inq_dimname(int \fIncid\fP, int \fIdimid\fP, char \fIname\fP[])\fR .HP \fBint nc_inq_dimlen(int \fIncid\fP, int \fIdimid\fP, size_t* \fIlen\fP)\fR .sp (Replace \fBncdiminq(\|)\fR in version 2) .sp Use these functions to find out about a dimension. If either the \fIname\fP argument or \fIlen\fP argument is a \fBNULL\fR pointer, then the associated information will not be returned. Otherwise, \fIname\fP should be big enough (\fBNC_MAX_NAME\fR) to hold the dimension name as the name will be copied into your storage. The length return parameter, \fIlen\fP will contain the size of the dimension. For the unlimited dimension, the returned length is the current maximum value used for writing into any of the variables which use the dimension. .HP \fBint nc_rename_dim(int \fIncid\fP, int \fIdimid\fP, const char \fIname\fP[])\fR .sp (Corresponds to \fBncdimrename(\|)\fR in version 2) .sp Renames an existing dimension in an open netCDF dataset. If the new name is longer than the old name, the netCDF dataset must be in define mode. You cannot rename a dimension to have the same name as another dimension. .HP \fBint nc_def_var(int \fIncid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, int \fIndims\fP, const int \fIdimids\fP[], int* \fIvarid\fP)\fR .sp (Corresponds to \fBncvardef(\|)\fR in version 2) .sp Adds a new variable to a netCDF dataset. The netCDF must be in define mode. If not \fBNULL\fR, then \fIvarid\fP will be set to the netCDF variable ID. .HP \fBint nc_inq_varid(int \fIncid\fP, const char \fIname\fP[], int* \fIvarid\fP)\fR .sp (Corresponds to \fBncvarid(\|)\fR in version 2) .sp Returns the ID of a netCDF variable in \fIvarid\fP given its name. .HP \fBint nc_inq_var(int \fIncid\fP, int \fIvarid\fP, char \fIname\fP[], nc_type* \fIxtype\fP, int* \fIndims\fP, int \fIdimids\fP[], int* \fInatts\fP)\fR .HP \fBint nc_inq_varname(int \fIncid\fP, int \fIvarid\fP, char \fIname\fP[])\fR .HP \fBint nc_inq_vartype(int \fIncid\fP, int \fIvarid\fP, nc_type* \fIxtype\fP)\fR .HP \fBint nc_inq_varndims(int \fIncid\fP, int \fIvarid\fP, int* \fIndims\fP)\fR .HP \fBint nc_inq_vardimid(int \fIncid\fP, int \fIvarid\fP, int \fIdimids\fP[])\fR .HP \fBint nc_inq_varnatts(int \fIncid\fP, int \fIvarid\fP, int* \fInatts\fP)\fR .sp (Replace \fBncvarinq(\|)\fR in version 2) .sp Returns information about a netCDF variable, given its ID. If any of the return parameters (\fIname\fP, \fIxtype\fP, \fIndims\fP, \fIdimids\fP, or \fInatts\fP) is a \fBNULL\fR pointer, then the corresponding information will not be returned; hence, no space need be allocated for it. .HP \fBint nc_rename_var(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[])\fR .sp (Corresponds to \fBncvarrename(\|)\fR in version 2) .sp Changes the name of a netCDF variable. If the new name is longer than the old name, the netCDF must be in define mode. You cannot rename a variable to have the name of any existing variable. .HP \fBint nc_put_var_text(int \fIncid\fP, int \fIvarid\fP, const char \fIout\fP[])\fR .HP \fBint nc_put_var_uchar(int \fIncid\fP, int \fIvarid\fP, const unsigned char \fIout\fP[])\fR .HP \fBint nc_put_var_schar(int \fIncid\fP, int \fIvarid\fP, const signed char \fIout\fP[])\fR .HP \fBint nc_put_var_short(int \fIncid\fP, int \fIvarid\fP, const short \fIout\fP[])\fR .HP \fBint nc_put_var_int(int \fIncid\fP, int \fIvarid\fP, const int \fIout\fP[])\fR .HP \fBint nc_put_var_long(int \fIncid\fP, int \fIvarid\fP, const long \fIout\fP[])\fR .HP \fBint nc_put_var_float(int \fIncid\fP, int \fIvarid\fP, const float \fIout\fP[])\fR .HP \fBint nc_put_var_double(int \fIncid\fP, int \fIvarid\fP, const double \fIout\fP[])\fR .sp (Replace \fBncvarput(\|)\fR in version 2) .sp Writes an entire netCDF variable (i.e. all the values). The netCDF dataset must be open and in data mode. The type of the data is specified in the function name, and it is converted to the external type of the specified variable, if possible, otherwise an \fBNC_ERANGE\fR error is returned. Note that rounding is not performed during the conversion. Floating point numbers are truncated when converted to integers. .HP \fBint nc_get_var_text(int \fIncid\fP, int \fIvarid\fP, char \fIin\fP[])\fR .HP \fBint nc_get_var_uchar(int \fIncid\fP, int \fIvarid\fP, unsigned char \fIin\fP[])\fR .HP \fBint nc_get_var_schar(int \fIncid\fP, int \fIvarid\fP, signed char \fIin\fP[])\fR .HP \fBint nc_get_var_short(int \fIncid\fP, int \fIvarid\fP, short \fIin\fP[])\fR .HP \fBint nc_get_var_int(int \fIncid\fP, int \fIvarid\fP, int \fIin\fP[])\fR .HP \fBint nc_get_var_long(int \fIncid\fP, int \fIvarid\fP, long \fIin\fP[])\fR .HP \fBint nc_get_var_float(int \fIncid\fP, int \fIvarid\fP, float \fIin\fP[])\fR .HP \fBint nc_get_var_double(int \fIncid\fP, int \fIvarid\fP, double \fIin\fP[])\fR .sp (Replace \fBncvarget(\|)\fR in version 2) .sp Reads an entire netCDF variable (i.e. all the values). The netCDF dataset must be open and in data mode. The data is converted from the external type of the specified variable, if necessary, to the type specified in the function name. If conversion is not possible, an \fBNC_ERANGE\fR error is returned. .HP \fBint nc_put_var1_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], char \fI*out\fP)\fR .HP \fBint nc_put_var1_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], unsigned char \fI*out\fP)\fR .HP \fBint nc_put_var1_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], signed char \fI*out\fP)\fR .HP \fBint nc_put_var1_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], short \fI*out\fP)\fR .HP \fBint nc_put_var1_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], int \fI*out\fP)\fR .HP \fBint nc_put_var1_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], long \fI*out\fP)\fR .HP \fBint nc_put_var1_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], float \fI*out\fP)\fR .HP \fBint nc_put_var1_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], double \fI*out\fP)\fR .sp (Replace \fBncvarput1(\|)\fR in version 2) .sp Puts a single data value into a variable at the position \fIindex\fP of an open netCDF dataset that is in data mode. The type of the data is specified in the function name, and it is converted to the external type of the specified variable, if possible, otherwise an \fBNC_ERANGE\fR error is returned. .HP \fBint nc_get_var1_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], char* \fIin\fP)\fR .HP \fBint nc_get_var1_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], unsigned char* \fIin\fP)\fR .HP \fBint nc_get_var1_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], signed char* \fIin\fP)\fR .HP \fBint nc_get_var1_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], short* \fIin\fP)\fR .HP \fBint nc_get_var1_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], int* \fIin\fP)\fR .HP \fBint nc_get_var1_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], long* \fIin\fP)\fR .HP \fBint nc_get_var1_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], float* \fIin\fP)\fR .HP \fBint nc_get_var1_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIindex\fP[], double* \fIin\fP)\fR .sp (Replace \fBncvarget1(\|)\fR in version 2) .sp Gets a single data value from a variable at the position \fIindex\fP of an open netCDF dataset that is in data mode. The data is converted from the external type of the specified variable, if necessary, to the type specified in the function name. If conversion is not possible, an \fBNC_ERANGE\fR error is returned. .HP \fBint nc_put_vara_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const char \fIout\fP[])\fR .HP \fBint nc_put_vara_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const unsigned char \fIout\fP[])\fR .HP \fBint nc_put_vara_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const signed char \fIout\fP[])\fR .HP \fBint nc_put_vara_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const short \fIout\fP[])\fR .HP \fBint nc_put_vara_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const int \fIout\fP[])\fR .HP \fBint nc_put_vara_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const long \fIout\fP[])\fR .HP \fBint nc_put_vara_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const float \fIout\fP[])\fR .HP \fBint nc_put_vara_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const double \fIout\fP[])\fR .sp (Replace \fBncvarput(\|)\fR in version 2) .sp Writes an array section of values into a netCDF variable of an open netCDF dataset, which must be in data mode. The array section is specified by the \fIstart\fP and \fIcount\fP vectors, which give the starting index and count of values along each dimension of the specified variable. The type of the data is specified in the function name and is converted to the external type of the specified variable, if possible, otherwise an \fBNC_ERANGE\fR error is returned. .HP \fBint nc_get_vara_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], char \fIin\fP[])\fR .HP \fBint nc_get_vara_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], unsigned char \fIin\fP[])\fR .HP \fBint nc_get_vara_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], signed char \fIin\fP[])\fR .HP \fBint nc_get_vara_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], short \fIin\fP[])\fR .HP \fBint nc_get_vara_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], int \fIin\fP[])\fR .HP \fBint nc_get_vara_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], long \fIin\fP[])\fR .HP \fBint nc_get_vara_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], float \fIin\fP[])\fR .HP \fBint nc_get_vara_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], double \fIin\fP[])\fR .sp (Corresponds to \fBncvarget(\|)\fR in version 2) .sp Reads an array section of values from a netCDF variable of an open netCDF dataset, which must be in data mode. The array section is specified by the \fIstart\fP and \fIcount\fP vectors, which give the starting index and count of values along each dimension of the specified variable. The data is converted from the external type of the specified variable, if necessary, to the type specified in the function name. If conversion is not possible, an \fBNC_ERANGE\fR error is returned. .HP \fBint nc_put_vars_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const char \fIout\fP[])\fR .HP \fBint nc_put_vars_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const unsigned char \fIout\fP[])\fR .HP \fBint nc_put_vars_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const signed char \fIout\fP[])\fR .HP \fBint nc_put_vars_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const short \fIout\fP[])\fR .HP \fBint nc_put_vars_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const int \fIout\fP[])\fR .HP \fBint nc_put_vars_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const long \fIout\fP[])\fR .HP \fBint nc_put_vars_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const float \fIout\fP[])\fR .HP \fBint nc_put_vars_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], const double \fIout\fP[])\fR .sp (Corresponds to \fBncvarputg(\|)\fR in version 2) .sp These functions are used for \fIstrided output\fP, which is like the array section output described above, except that the sampling stride (the interval between accessed values) is specified for each dimension. For an explanation of the sampling stride vector, see COMMON ARGUMENTS DESCRIPTIONS below. .HP \fBint nc_get_vars_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], char \fIin\fP[])\fR .HP \fBint nc_get_vars_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], unsigned char \fIin\fP[])\fR .HP \fBint nc_get_vars_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], signed char \fIin\fP[])\fR .HP \fBint nc_get_vars_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], short \fIin\fP[])\fR .HP \fBint nc_get_vars_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], int \fIin\fP[])\fR .HP \fBint nc_get_vars_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], long \fIin\fP[])\fR .HP \fBint nc_get_vars_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], float \fIin\fP[])\fR .HP \fBint nc_get_vars_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], double \fIin\fP[])\fR .sp (Corresponds to \fBncvargetg(\|)\fR in version 2) .sp These functions are used for \fIstrided input\fP, which is like the array section input described above, except that the sampling stride (the interval between accessed values) is specified for each dimension. For an explanation of the sampling stride vector, see COMMON ARGUMENTS DESCRIPTIONS below. .HP \fBint nc_put_varm_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const char \fIout\fP[])\fR .HP \fBint nc_put_varm_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const unsigned char \fIout\fP[])\fR .HP \fBint nc_put_varm_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const signed char \fIout\fP[])\fR .HP \fBint nc_put_varm_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const short \fIout\fP[])\fR .HP \fBint nc_put_varm_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const int \fIout\fP[])\fR .HP \fBint nc_put_varm_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const long \fIout\fP[])\fR .HP \fBint nc_put_varm_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const float \fIout\fP[])\fR .HP \fBint nc_put_varm_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, const double \fIout\fP[])\fR .sp (Corresponds to \fBncvarputg(\|)\fR in version 2) .sp These functions are used for \fImapped output\fP, which is like strided output described above, except that an additional index mapping vector is provided to specify the in-memory arrangement of the data values. For an explanation of the index mapping vector, see COMMON ARGUMENTS DESCRIPTIONS below. .HP \fBint nc_get_varm_text(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, char \fIin\fP[])\fR .HP \fBint nc_get_varm_uchar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, unsigned char \fIin\fP[])\fR .HP \fBint nc_get_varm_schar(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, signed char \fIin\fP[])\fR .HP \fBint nc_get_varm_short(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, short \fIin\fP[])\fR .HP \fBint nc_get_varm_int(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, int \fIin\fP[])\fR .HP \fBint nc_get_varm_long(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, long \fIin\fP[])\fR .HP \fBint nc_get_varm_float(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, float \fIin\fP[])\fR .HP \fBint nc_get_varm_double(int \fIncid\fP, int \fIvarid\fP, const size_t \fIstart\fP[], const size_t \fIcount\fP[], const size_t \fIstride\fP[], \fIimap\fP, double \fIin\fP[])\fR .sp (Corresponds to \fBncvargetg(\|)\fR in version 2) .sp These functions are used for \fImapped input\fP, which is like strided input described above, except that an additional index mapping vector is provided to specify the in-memory arrangement of the data values. For an explanation of the index mapping vector, see COMMON ARGUMENTS DESCRIPTIONS below. .HP \fBint nc_put_att_text(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const char \fIout\fP[])\fR .HP \fBint nc_put_att_uchar(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const unsigned char \fIout\fP[])\fR .HP \fBint nc_put_att_schar(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const signed char \fIout\fP[])\fR .HP \fBint nc_put_att_short(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const short \fIout\fP[])\fR .HP \fBint nc_put_att_int(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const int \fIout\fP[])\fR .HP \fBint nc_put_att_long(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const long \fIout\fP[])\fR .HP \fBint nc_put_att_float(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const float \fIout\fP[])\fR .HP \fBint nc_put_att_double(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type \fIxtype\fP, size_t \fIlen\fP, const double \fIout\fP[])\fR .sp (Replace \fBncattput(\|)\fR in version 2) .sp Unlike variables, attributes do not have separate functions for defining and writing values. This family of functions defines a new attribute with a value or changes the value of an existing attribute. If the attribute is new, or if the space required to store the attribute value is greater than before, the netCDF dataset must be in define mode. The parameter \fIlen\fP is the number of values from \fIout\fP to transfer. It is often one, except that for \fBnc_put_att_text(\|)\fR it will usually be \fBstrlen(\fIout\fP)\fR. .sp For these functions, the type component of the function name refers to the in-memory type of the value, whereas the \fIxtype\fP argument refers to the external type for storing the value. An \fBNC_ERANGE\fR error results if a conversion between these types is not possible. In this case the value is represented with the appropriate fill-value for the associated external type. .HP \fBint nc_inq_attname(int \fIncid\fP, int \fIvarid\fP, int \fIattnum\fP, char \fIname\fP[])\fR .sp (Corresponds to \fBncattname(\|)\fR in version 2) .sp Gets the name of an attribute, given its variable ID and attribute number. This function is useful in generic applications that need to get the names of all the attributes associated with a variable, since attributes are accessed by name rather than number in all other attribute functions. The number of an attribute is more volatile than the name, since it can change when other attributes of the same variable are deleted. The attributes for each variable are numbered from 0 (the first attribute) to \fInvatts\fP-1, where \fInvatts\fP is the number of attributes for the variable, as returned from a call to \fBnc_inq_varnatts(\|)\fR. If the \fIname\fP parameter is a \fBNULL\fR pointer, no name will be returned and no space need be allocated. .HP \fBint nc_inq_att(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type* \fIxtype\fP, size_t* \fIlen\fP)\fR .HP \fBint nc_inq_attid(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], int* \fIattnum\fP)\fR .HP \fBint nc_inq_atttype(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], nc_type* \fIxtype\fP)\fR .HP \fBint nc_inq_attlen(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], size_t* \fIlen\fP)\fR .sp (Corresponds to \fBncattinq(\|)\fR in version 2) .sp These functions return information about a netCDF attribute, given its variable ID and name. The information returned is the external type in \fIxtype\fP and the number of elements in the attribute as \fIlen\fP. If any of the return arguments is a \fBNULL\fR pointer, the specified information will not be returned. .HP \fBint nc_copy_att(int \fIncid\fP, int \fIvarid_in\fP, const char \fIname\fP[], int \fIncid_out\fP, int \fIvarid_out\fP)\fR .sp (Corresponds to \fBncattcopy(\|)\fR in version 2) .sp Copies an attribute from one netCDF dataset to another. It can also be used to copy an attribute from one variable to another within the same netCDF. \fIncid_in\fP is the netCDF ID of an input netCDF dataset from which the attribute will be copied. \fIvarid_in\fP is the ID of the variable in the input netCDF dataset from which the attribute will be copied, or \fBNC_GLOBAL\fR for a global attribute. \fIname\fP is the name of the attribute in the input netCDF dataset to be copied. \fIncid_out\fP is the netCDF ID of the output netCDF dataset to which the attribute will be copied. It is permissible for the input and output netCDF ID's to be the same. The output netCDF dataset should be in define mode if the attribute to be copied does not already exist for the target variable, or if it would cause an existing target attribute to grow. \fIvarid_out\fP is the ID of the variable in the output netCDF dataset to which the attribute will be copied, or \fBNC_GLOBAL\fR to copy to a global attribute. .HP \fBint nc_rename_att(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], const char \fInewname\fP[])\fR .sp (Corresponds to \fBncattrename(\|)\fR .sp Changes the name of an attribute. If the new name is longer than the original name, the netCDF must be in define mode. You cannot rename an attribute to have the same name as another attribute of the same variable. \fIname\fP is the original attribute name. \fInewname\fP is the new name to be assigned to the specified attribute. If the new name is longer than the old name, the netCDF dataset must be in define mode. .HP \fBint nc_del_att(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[])\fR .sp (Corresponds to \fBncattdel(\|)\fR in version 2) .sp Deletes an attribute from a netCDF dataset. The dataset must be in define mode. .HP \fBint nc_get_att_text(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], char \fIin\fP[])\fR .HP \fBint nc_get_att_uchar(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], unsigned char \fIin\fP[])\fR .HP \fBint nc_get_att_schar(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], signed char \fIin\fP[])\fR .HP \fBint nc_get_att_short(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], short \fIin\fP[])\fR .HP \fBint nc_get_att_int(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], int \fIin\fP[])\fR .HP \fBint nc_get_att_long(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], long \fIin\fP[])\fR .HP \fBint nc_get_att_float(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], float \fIin\fP[])\fR .HP \fBint nc_get_att_double(int \fIncid\fP, int \fIvarid\fP, const char \fIname\fP[], double \fIin\fP[])\fR .sp (Replace \fBncattget(\|)\fR in version 2) .sp Gets the value(s) of a netCDF attribute, given its variable ID and name. Converts from the external type to the type specified in the function name, if possible, otherwise returns an \fBNC_ERANGE\fR error. All elements of the vector of attribute values are returned, so you must allocate enough space to hold them. If you don't know how much space to reserve, call \fBnc_inq_attlen(\|)\fR first to find out the length of the attribute. .SH "COMMON ARGUMENT DESCRIPTIONS" .LP In this section we define some common arguments which are used in the "FUNCTION DESCRIPTIONS" section. .TP int \fIncid\fP is the netCDF ID returned from a previous, successful call to \fBnc_open(\|)\fR or \fBnc_create(\|)\fR .TP char \fIname\fP[] is the name of a dimension, variable, or attribute. The names of dimensions, variables and attributes consist of arbitrary sequences of alphanumeric characters (as well as underscore '_', period '.' and hyphen '-'), beginning with a letter or underscore. (However names commencing with underscore are reserved for system use.) Case is significant in netCDF names. A zero-length name is not allowed. As an input argument, it shall be a pointer to a 0-terminated string; as an output argument, it shall be the address of a buffer in which to hold such a string. The maximum allowable number of characters (excluding the terminating 0) is \fBNC_MAX_NAME\fR. .TP nc_type \fIxtype\fP specifies the external data type of a netCDF variable or attribute and is one of the following: \fBNC_BYTE\fR, \fBNC_CHAR\fR, \fBNC_SHORT\fR, \fBNC_INT\fR, \fBNC_FLOAT\fR, or \fBNC_DOUBLE\fR. These are used to specify 8-bit integers, characters, 16-bit integers, 32-bit integers, 32-bit IEEE floating point numbers, and 64-bit IEEE floating-point numbers, respectively. (\fBNC_INT\fR corresponds to \fBNC_LONG\fR in version 2, to specify a 32-bit integer). .TP int \fIdimids\fP[] is a vector of dimension ID's and defines the shape of a netCDF variable. The size of the vector shall be greater than or equal to the rank (i.e. the number of dimensions) of the variable (\fIndims\fP). The vector shall be ordered by the speed with which a dimension varies: \fIdimids\fP[\fIndims\fP-1] shall be the dimension ID of the most rapidly varying dimension and \fIdimids\fP[0] shall be the dimension ID of the most slowly varying dimension. The maximum possible number of dimensions for a variable is given by the symbolic constant \fBNC_MAX_VAR_DIMS\fR. .TP int \fIdimid\fP is the ID of a netCDF dimension. netCDF dimension ID's are allocated sequentially from the non-negative integers beginning with 0. .TP int \fIndims\fP is either the total number of dimensions in a netCDF dataset or the rank (i.e. the number of dimensions) of a netCDF variable. The value shall not be negative or greater than the symbolic constant \fBNC_MAX_VAR_DIMS\fR. .TP int \fIvarid\fP is the ID of a netCDF variable or (for the attribute-access functions) the symbolic constant \fBNC_GLOBAL\fR, which is used to reference global attributes. netCDF variable ID's are allocated sequentially from the non-negative integers beginning with 0. .TP int* \fInatts\fP is the number of global attributes in a netCDF dataset for the \fBnc_inquire(\|)\fR function or the number of attributes associated with a netCDF variable for the \fBnc_varinq(\|)\fR function. .TP const size_t \fIindex\fP[] specifies the indicial coordinates of the netCDF data value to be accessed. The indices start at 0; thus, for example, the first data value of a two-dimensional variable is (0,0). The size of the vector shall be at least the rank of the associated netCDF variable and its elements shall correspond, in order, to the variable's dimensions. .TP const size_t \fIstart\fP[] specifies the starting point for accessing a netCDF variable's data values in terms of the indicial coordinates of the corner of the array section. The indices start at 0; thus, the first data value of a variable is (0, 0, ..., 0). The size of the vector shall be at least the rank of the associated netCDF variable and its elements shall correspond, in order, to the variable's dimensions. .TP const size_t \fIcount\fP[] specifies the number of indices selected along each dimension of the array section. Thus, to access a single value, for example, specify \fIcount\fP as (1, 1, ..., 1). Note that, for strided I/O, this argument must be adjusted to be compatible with the \fIstride\fP and \fIstart\fP arguments so that the interaction of the three does not attempt to access an invalid data co-ordinate. The elements of the \fIcount\fP vector correspond, in order, to the variable's dimensions. .TP const size_t \fIstride\fP[] specifies the sampling interval along each dimension of the netCDF variable. The elements of the stride vector correspond, in order, to the netCDF variable's dimensions (\fIstride\fP[0]) gives the sampling interval along the most slowly varying dimension of the netCDF variable). Sampling intervals are specified in type-independent units of elements (a value of 1 selects consecutive elements of the netCDF variable along the corresponding dimension, a value of 2 selects every other element, etc.). A \fBNULL\fR stride argument is treated as (1, 1, ... , 1). .TP \fIimap\fP specifies the mapping between the dimensions of a netCDF variable and the in-memory structure of the internal data array. The elements of the index mapping vector correspond, in order, to the netCDF variable's dimensions (\fIimap\fP[0] gives the distance between elements of the internal array corresponding to the most slowly varying dimension of the netCDF variable). Distances between elements are specified in type-independent units of elements (the distance between internal elements that occupy adjacent memory locations is 1 and not the element's byte-length as in netCDF 2). A \fBNULL\fR pointer means the memory-resident values have the same structure as the associated netCDF variable. .SH "VARIABLE PREFILLING" .LP By default, the netCDF interface sets the values of all newly-defined variables of finite length (i.e. those that do not have an unlimited, dimension) to the type-dependent fill-value associated with each variable. This is done when \fBnc_enddef(\|)\fR is called. The fill-value for a variable may be changed from the default value by defining the attribute `\fB_FillValue\fR' for the variable. This attribute must have the same type as the variable and be of length one. .LP Variables with an unlimited dimension are also prefilled, but on an `as needed' basis. For example, if the first write of such a variable is to position 5, then positions 0 through 4 (and no others) would be set to the fill-value at the same time. .LP This default prefilling of data values may be disabled by or'ing the \fBNC_NOFILL\fR flag into the mode parameter of \fBnc_open(\|)\fR or \fBnc_create(\|)\fR, or, by calling the function \fBnc_set_fill(\|)\fR with the argument \fBNC_NOFILL\fR. For variables that do not use the unlimited dimension, this call must be made before \fBnc_enddef(\|)\fR. For variables that use the unlimited dimension, this call may be made at any time. .LP One can obtain increased performance of the netCDF interface by using this feature, but only at the expense of requiring the application to set every single data value. The performance enhancing behavior of this function is dependent on the particulars of the implementation and dataset format. The flag value controlled by \fBnc_set_fill(\|)\fR is per netCDF ID, not per variable or per write. Allowing this to change affects the degree to which a program can be effectively parallelized. Given all of this, we state that the use of this feature may not be available (or even needed) in future releases. Programmers are cautioned against heavy reliance upon this feature. .HP \fBint nc_setfill(int \fIncid\fP, int \fIfillmode\fP, int* \fIold_fillemode\fP)\fR .sp (Corresponds to \fBncsetfill(\|)\fR in version 2) .sp Determines whether or not variable prefilling will be done (see above). The netCDF dataset shall be writable. \fIfillmode\fP is either \fBNC_FILL\fR to enable prefilling (the default) or \fBNC_NOFILL\fR to disable prefilling. This function returns the previous setting in \fIold_fillmode\fP. .SH "MPP FUNCTION DESCRIPTIONS" .LP Additional functions for use on SGI/Cray MPP machines (_CRAYMPP). These are used to set and inquire which PE is the base for MPP for a particular netCDF. These are only relevant when using the SGI/Cray ``global'' Flexible File I/O layer and desire to have only a subset of PEs to open the specific netCDF file. For technical reasons, these functions are available on all platforms. On a platform other than SGI/Cray MPP, it is as if only processor available were processor 0. .LP To use this feature, you need to specify a communicator group and call \fBglio_group_mpi(\|)\fR or \fBglio_group_shmem(\|)\fR prior to the netCDF \fBnc_open(\|)\fR and \fBnc_create(\|)\fR calls. .HP \fBint nc__create_mp(const char \fIpath\fP[], int \fIcmode\fP, size_t \fIinitialsize\fP, int \fIpe\fP, size_t* \fIchunksize\fP, int* \fIncid\fP)\fR .sp Like \fBnc__create(\|)\fR but allows the base PE to be set. .sp The argument \fIpe\fP sets the base PE at creation time. In the MPP environment, \fBnc__create(\|)\fR and \fBnc_create(\|)\fR set the base PE to processor zero by default. .HP \fBint nc__open_mp(const char \fIpath\fP[], int \fImode\fP, int \fIpe\fP, size_t* \fIchunksize\fP, int* \fIncid\fP)\fR .sp Like \fBnc__open(\|)\fR but allows the base PE to be set. The argument \fIpe\fP sets the base PE at creation time. In the MPP environment, \fBnc__open(\|)\fR and \fBnc_open(\|)\fR set the base PE to processor zero by default. .HP \fBint nc_inq_base_pe(int \fIncid\fP, int* \fIpe\fP)\fR .sp Inquires of the netCDF dataset which PE is being used as the base for MPP use. This is safe to use at any time. .HP \fBint nc_set_base_pe(int \fIncid\fP, int \fIpe\fP)\fR .sp Resets the base PE for the netCDF dataset. Only perform this operation when the affected communicator group synchronizes before and after the call. This operation is very risky and should only be contemplated under only the most extreme cases. .SH "ENVIRONMENT VARIABLES" .TP 4 .B NETCDF_FFIOSPEC Specifies the Flexible File I/O buffers for netCDF I/O when executing under the UNICOS operating system (the variable is ignored on other operating systems). An appropriate specification can greatly increase the efficiency of netCDF I/O -- to the extent that it can actually surpass FORTRAN binary I/O. This environment variable has been made a little more generalized, such that other FFIO option specifications can now be added. The default specification is \fBbufa:336:2\fP, unless a current FFIO specification is in operation, which will be honored. See UNICOS Flexible File I/O for more information. .SH "MAILING-LISTS" .LP Both a mailing list and a digest are available for discussion of the netCDF interface and announcements about netCDF bugs, fixes, and enhancements. To begin or change your subscription to either the mailing-list or the digest, send one of the following in the body (not the subject line) of an email message to "majordomo@unidata.ucar.edu". Use your email address in place of \fIjdoe@host.inst.domain\fP. .sp To subscribe to the netCDF mailing list: .RS \fBsubscribe netcdfgroup \fIjdoe@host.inst.domain\fR .RE To unsubscribe from the netCDF mailing list: .RS \fBunsubscribe netcdfgroup \fIjdoe@host.inst.domain\fR .RE To subscribe to the netCDF digest: .RS \fBsubscribe netcdfdigest \fIjdoe@host.inst.domain\fR .RE To unsubscribe from the netCDF digest: .RS \fBunsubscribe netcdfdigest \fIjdoe@host.inst.domain\fR .RE To retrieve the general introductory information for the mailing list: .RS \fBinfo netcdfgroup\fR .RE To get a synopsis of other majordomo commands: .RS \fBhelp\fR .RE .SH "SEE ALSO" .LP .BR ncdump (1), .BR ncgen (1), .BR netcdf (3), .BR netcdf_f77 (3), .BR netcdf_f90 (3)). .LP \fInetCDF User's Guide\fP, published by the Unidata Program Center, University Corporation for Atmospheric Research, located in Boulder, Colorado. xdmf-2.1.dfsg.1/Utilities/vtknetcdf/putget.c0000644000175000017500000100057511606020250022144 0ustar amckinstryamckinstry/* Do not edit this file. It is produced from the corresponding .m4 source */ /* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: putget.c,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #include "nc.h" #include #include #include #include "ncx.h" #include "fbits.h" #include "onstack.h" #ifdef LOCKNUMREC # include /* for SGI/Cray SHMEM routines */ # ifdef LN_TEST # include # endif #endif #ifdef __BORLANDC__ # pragma warn -8004 /* "assigned a value that is never used" */ # pragma warn -8065 /* "Call to function 'XXX' with no prototype" */ #endif #if defined(_MSC_VER) && (_MSC_VER >= 1400) # pragma warning ( disable : 4130 ) /* logical operation on address of string constant */ #endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ #undef MIN /* system may define MIN somewhere and complain */ #define MIN(mm,nn) (((mm) < (nn)) ? (mm) : (nn)) /* #define ODEBUG 1 */ #if ODEBUG #include /* * Print the values of an array of size_t */ void arrayp(const char *label, size_t count, const size_t *array) { (void) fprintf(stderr, "%s", label); (void) fputc('\t',stderr); for(; count > 0; count--, array++) (void) fprintf(stderr," %lu", (unsigned long)*array); (void) fputc('\n',stderr); } #endif /* ODEBUG */ /* * This is how much space is required by the user, as in * * vals = malloc(nel * nctypelen(var.type)); * ncvarget(cdfid, varid, cor, edg, vals); */ int nctypelen(nc_type type) { switch(type){ case NC_BYTE : case NC_CHAR : return((int)sizeof(char)); case NC_SHORT : return(int)(sizeof(short)); case NC_INT : return((int)sizeof(int)); case NC_FLOAT : return((int)sizeof(float)); case NC_DOUBLE : return((int)sizeof(double)); case NC_NAT: break; /* some compilers complain if enums are missing from a switch */ } return -1; } /* Begin fill */ /* * This is tunable parameter. * It essentially controls the tradeoff between the number of times * memcpy() gets called to copy the external data to fill * a large buffer vs the number of times its called to * prepare the external data. */ #if _SX /* NEC SX specific optimization */ #define NFILL 2048 #else #define NFILL 16 #endif /* * Next 6 type specific functions * Fill a some memory with the default special value. * Formerly NC_arrayfill() */ static int NC_fill_schar( void **xpp, size_t nelems) /* how many */ { schar fillp[NFILL * sizeof(double)/X_SIZEOF_CHAR]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { schar *vp = fillp; /* lower bound of area to be filled */ const schar *const end = vp + nelems; while(vp < end) { *vp++ = NC_FILL_BYTE; } } return ncx_putn_schar_schar(xpp, nelems, fillp); } static int NC_fill_char( void **xpp, size_t nelems) /* how many */ { char fillp[NFILL * sizeof(double)/X_SIZEOF_CHAR]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { char *vp = fillp; /* lower bound of area to be filled */ const char *const end = vp + nelems; while(vp < end) { *vp++ = NC_FILL_CHAR; } } return ncx_putn_char_char(xpp, nelems, fillp); } static int NC_fill_short( void **xpp, size_t nelems) /* how many */ { short fillp[NFILL * sizeof(double)/X_SIZEOF_SHORT]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { short *vp = fillp; /* lower bound of area to be filled */ const short *const end = vp + nelems; while(vp < end) { *vp++ = NC_FILL_SHORT; } } return ncx_putn_short_short(xpp, nelems, fillp); } #if (SIZEOF_INT >= X_SIZEOF_INT) static int NC_fill_int( void **xpp, size_t nelems) /* how many */ { int fillp[NFILL * sizeof(double)/X_SIZEOF_INT]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { int *vp = fillp; /* lower bound of area to be filled */ const int *const end = vp + nelems; while(vp < end) { *vp++ = NC_FILL_INT; } } return ncx_putn_int_int(xpp, nelems, fillp); } #elif SIZEOF_LONG == X_SIZEOF_INT static int NC_fill_int( void **xpp, size_t nelems) /* how many */ { long fillp[NFILL * sizeof(double)/X_SIZEOF_INT]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { long *vp = fillp; /* lower bound of area to be filled */ const long *const end = vp + nelems; while(vp < end) { *vp++ = NC_FILL_INT; } } return ncx_putn_int_long(xpp, nelems, fillp); } #else #error "NC_fill_int implementation" #endif static int NC_fill_float( void **xpp, size_t nelems) /* how many */ { float fillp[NFILL * sizeof(double)/X_SIZEOF_FLOAT]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { float *vp = fillp; /* lower bound of area to be filled */ const float *const end = vp + nelems; while(vp < end) { *vp++ = NC_FILL_FLOAT; } } return ncx_putn_float_float(xpp, nelems, fillp); } static int NC_fill_double( void **xpp, size_t nelems) /* how many */ { double fillp[NFILL * sizeof(double)/X_SIZEOF_DOUBLE]; assert(nelems <= sizeof(fillp)/sizeof(fillp[0])); { double *vp = fillp; /* lower bound of area to be filled */ const double *const end = vp + nelems; while(vp < end) { *vp++ = NC_FILL_DOUBLE; } } return ncx_putn_double_double(xpp, nelems, fillp); } /* * Fill the external space for variable 'varp' values at 'recno' with * the appropriate value. If 'varp' is not a record variable, fill the * whole thing. For the special case when 'varp' is the only record * variable and it is of type byte, char, or short, varsize should be * ncp->recsize, otherwise it should be varp->len. * Formerly xdr_NC_fill() */ int fill_NC_var(NC *ncp, const NC_var *varp, size_t varsize, size_t recno) { char xfillp[NFILL * X_SIZEOF_DOUBLE]; const size_t step = varp->xsz; const size_t nelems = sizeof(xfillp)/step; const size_t xsz = varp->xsz * nelems; NC_attr **attrpp; off_t offset; size_t remaining = varsize; void *xp; int status; /* * Set up fill value */ attrpp = NC_findattr(&varp->attrs, _FillValue); if( attrpp != NULL ) { /* User defined fill value */ if( (*attrpp)->type != varp->type || (*attrpp)->nelems != 1 ) { return NC_EBADTYPE; } else { /* Use the user defined value */ char *cp = xfillp; const char *const end = &xfillp[sizeof(xfillp)]; assert(step <= (*attrpp)->xsz); for( /*NADA*/; cp < end; cp += step) { (void) memcpy(cp, (*attrpp)->xvalue, step); } } } else { /* use the default */ assert(xsz % X_ALIGN == 0); assert(xsz <= sizeof(xfillp)); xp = xfillp; switch(varp->type){ case NC_BYTE : status = NC_fill_schar(&xp, nelems); break; case NC_CHAR : status = NC_fill_char(&xp, nelems); break; case NC_SHORT : status = NC_fill_short(&xp, nelems); break; case NC_INT : status = NC_fill_int(&xp, nelems); break; case NC_FLOAT : status = NC_fill_float(&xp, nelems); break; case NC_DOUBLE : status = NC_fill_double(&xp, nelems); break; default : assert("fill_NC_var invalid type" == 0); status = NC_EBADTYPE; break; } if(status != NC_NOERR) return status; assert(xp == xfillp + xsz); } /* * copyout: * xfillp now contains 'nelems' elements of the fill value * in external representation. */ /* * Copy it out. */ offset = varp->begin; if(IS_RECVAR(varp)) { offset += (off_t)ncp->recsize * recno; } assert(remaining > 0); for(;;) { const size_t chunksz = MIN(remaining, ncp->chunk); size_t ii; status = ncp->nciop->get(ncp->nciop, offset, chunksz, RGN_WRITE, &xp); if(status != NC_NOERR) { return status; } /* * fill the chunksz buffer in units of xsz */ for(ii = 0; ii < chunksz/xsz; ii++) { (void) memcpy(xp, xfillp, xsz); xp = (char *)xp + xsz; } /* * Deal with any remainder */ { const size_t rem = chunksz % xsz; if(rem != 0) { (void) memcpy(xp, xfillp, rem); /* xp = (char *)xp + xsz; */ } } status = ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); if(status != NC_NOERR) { break; } remaining -= chunksz; if(remaining == 0) break; /* normal loop exit */ offset += chunksz; } return status; } /* End fill */ /* * Add a record containing the fill values. */ static int NCfillrecord(NC *ncp, const NC_var *const *varpp, size_t recno) { size_t ii = 0; for(; ii < ncp->vars.nelems; ii++, varpp++) { if( !IS_RECVAR(*varpp) ) { continue; /* skip non-record variables */ } { const int status = fill_NC_var(ncp, *varpp, (*varpp)->len, recno); if(status != NC_NOERR) return status; } } return NC_NOERR; } /* * Add a record containing the fill values in the special case when * there is exactly one record variable, where we don't require each * record to be four-byte aligned (no record padding). */ static int NCfillspecialrecord(NC *ncp, const NC_var *varp, size_t recno) { int status; assert(IS_RECVAR(varp)); status = fill_NC_var(ncp, varp, ncp->recsize, recno); if(status != NC_NOERR) return status; return NC_NOERR; } /* * It is advantageous to * #define TOUCH_LAST * when using memory mapped io. */ #if TOUCH_LAST /* * Grow the file to a size which can contain recno */ static int NCtouchlast(NC *ncp, const NC_var *const *varpp, size_t recno) { int status = NC_NOERR; const NC_var *varp = NULL; { size_t ii = 0; for(; ii < ncp->vars.nelems; ii++, varpp++) { if( !IS_RECVAR(*varpp) ) { continue; /* skip non-record variables */ } varp = *varpp; } } assert(varp != NULL); assert( IS_RECVAR(varp) ); { const off_t offset = varp->begin + (off_t)(recno-1) * (off_t)ncp->recsize + (off_t)(varp->len - varp->xsz); void *xp; status = ncp->nciop->get(ncp->nciop, offset, varp->xsz, RGN_WRITE, &xp); if(status != NC_NOERR) return status; (void)memset(xp, 0, varp->xsz); status = ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); } return status; } #endif /* TOUCH_LAST */ /* * Ensure that the netcdf file has 'numrecs' records, * add records and fill as neccessary. */ static int NCvnrecs(NC *ncp, size_t numrecs) { int status = NC_NOERR; #ifdef LOCKNUMREC ushmem_t myticket = 0, nowserving = 0; ushmem_t numpe = (ushmem_t) _num_pes(); /* get ticket and wait */ myticket = shmem_short_finc((shmem_t *) ncp->lock + LOCKNUMREC_LOCK, ncp->lock[LOCKNUMREC_BASEPE]); #ifdef LN_TEST fprintf(stderr,"%d of %d : ticket = %hu\n", _my_pe(), _num_pes(), myticket); #endif do { shmem_short_get((shmem_t *) &nowserving, (shmem_t *) ncp->lock + LOCKNUMREC_SERVING, 1, ncp->lock[LOCKNUMREC_BASEPE]); #ifdef LN_TEST fprintf(stderr,"%d of %d : serving = %hu\n", _my_pe(), _num_pes(), nowserving); #endif /* work-around for non-unique tickets */ if (nowserving > myticket && nowserving < myticket + numpe ) { /* get a new ticket ... you've been bypassed */ /* and handle the unlikely wrap-around effect */ myticket = shmem_short_finc( (shmem_t *) ncp->lock + LOCKNUMREC_LOCK, ncp->lock[LOCKNUMREC_BASEPE]); #ifdef LN_TEST fprintf(stderr,"%d of %d : new ticket = %hu\n", _my_pe(), _num_pes(), myticket); #endif } } while(nowserving != myticket); /* now our turn to check & update value */ #endif if(numrecs > NC_get_numrecs(ncp)) { #if TOUCH_LAST status = NCtouchlast(ncp, (const NC_var *const*)ncp->vars.value, numrecs); if(status != NC_NOERR) goto common_return; #endif /* TOUCH_LAST */ set_NC_ndirty(ncp); if(!NC_dofill(ncp)) { /* Simply set the new numrecs value */ NC_set_numrecs(ncp, numrecs); } else { /* Treat two cases differently: - exactly one record variable (no padding) - multiple record variables (each record padded to 4-byte alignment) */ NC_var **vpp = (NC_var **)ncp->vars.value; NC_var *const *const end = &vpp[ncp->vars.nelems]; NC_var *recvarp = NULL; /* last record var */ int numrecvars = 0; size_t cur_nrecs; /* determine how many record variables */ for( /*NADA*/; vpp < end; vpp++) { if(IS_RECVAR(*vpp)) { recvarp = *vpp; numrecvars++; } } if (numrecvars != 1) { /* usual case */ /* Fill each record out to numrecs */ while((cur_nrecs = NC_get_numrecs(ncp)) < numrecs) { status = NCfillrecord(ncp, (const NC_var *const*)ncp->vars.value, cur_nrecs); if(status != NC_NOERR) { break; } NC_increase_numrecs(ncp, cur_nrecs +1); } if(status != NC_NOERR) goto common_return; } else { /* special case */ /* Fill each record out to numrecs */ while((cur_nrecs = NC_get_numrecs(ncp)) < numrecs) { status = NCfillspecialrecord(ncp, recvarp, cur_nrecs); if(status != NC_NOERR) { break; } NC_increase_numrecs(ncp, cur_nrecs +1); } if(status != NC_NOERR) goto common_return; } } if(NC_doNsync(ncp)) { status = write_numrecs(ncp); } } common_return: #ifdef LOCKNUMREC /* finished with our lock - increment serving number */ (void) shmem_short_finc((shmem_t *) ncp->lock + LOCKNUMREC_SERVING, ncp->lock[LOCKNUMREC_BASEPE]); #endif return status; } /* * Check whether 'coord' values are valid for the variable. */ static int NCcoordck(NC *ncp, const NC_var *varp, const size_t *coord) { const size_t *ip; size_t *up; if(varp->ndims == 0) return NC_NOERR; /* 'scalar' variable */ if(IS_RECVAR(varp)) { if(*coord > X_INT_MAX) return NC_EINVALCOORDS; /* sanity check */ if(NC_readonly(ncp) && *coord >= NC_get_numrecs(ncp)) { if(!NC_doNsync(ncp)) return NC_EINVALCOORDS; /* else */ { /* Update from disk and check again */ const int status = read_numrecs(ncp); if(status != NC_NOERR) return status; if(*coord >= NC_get_numrecs(ncp)) return NC_EINVALCOORDS; } } ip = coord + 1; up = varp->shape + 1; } else { ip = coord; up = varp->shape; } #ifdef CDEBUG fprintf(stderr," NCcoordck: coord %ld, count %d, ip %ld\n", coord, varp->ndims, ip ); #endif /* CDEBUG */ for(; ip < coord + varp->ndims; ip++, up++) { #ifdef CDEBUG fprintf(stderr," NCcoordck: ip %p, *ip %ld, up %p, *up %lu\n", ip, *ip, up, *up ); #endif /* CDEBUG */ /* cast needed for braindead systems with signed size_t */ if((unsigned long) *ip >= (unsigned long) *up ) return NC_EINVALCOORDS; } return NC_NOERR; } /* * Check whether 'edges' are valid for the variable and 'start' */ /*ARGSUSED*/ static int NCedgeck(const NC *ncp, const NC_var *varp, const size_t *start, const size_t *edges) { const size_t *const end = start + varp->ndims; const size_t *shp = varp->shape; (void)ncp; if(varp->ndims == 0) return NC_NOERR; /* 'scalar' variable */ if(IS_RECVAR(varp)) { start++; edges++; shp++; } for(; start < end; start++, edges++, shp++) { /* cast needed for braindead systems with signed size_t */ if((unsigned long) *edges > *shp || (unsigned long) *start + (unsigned long) *edges > *shp) { return(NC_EEDGE); } } return NC_NOERR; } /* * Translate the (variable, coord) pair into a seek index */ static off_t NC_varoffset(const NC *ncp, const NC_var *varp, const size_t *coord) { if(varp->ndims == 0) /* 'scalar' variable */ return varp->begin; if(varp->ndims == 1) { if(IS_RECVAR(varp)) return varp->begin + (off_t)(*coord) * (off_t)ncp->recsize; /* else */ return varp->begin + (off_t)(*coord) * (off_t)varp->xsz; } /* else */ { off_t lcoord = (off_t)coord[varp->ndims -1]; size_t *up = varp->dsizes +1; const size_t *ip = coord; const size_t *const end = varp->dsizes + varp->ndims; if(IS_RECVAR(varp)) up++, ip++; for(; up < end; up++, ip++) lcoord += *up * *ip; lcoord *= varp->xsz; if(IS_RECVAR(varp)) lcoord += (off_t)(*coord) * ncp->recsize; lcoord += varp->begin; return lcoord; } } static int putNCvx_char_char(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const char *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_char_char(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_schar_schar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_schar_schar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_schar_uchar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_schar_uchar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_schar_short(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_schar_short(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_schar_int(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_schar_int(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_schar_long(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_schar_long(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_schar_float(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_schar_float(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_schar_double(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_schar_double(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_short_schar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_short_schar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_short_uchar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_short_uchar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_short_short(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_short_short(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_short_int(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_short_int(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_short_long(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_short_long(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_short_float(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_short_float(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_short_double(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_short_double(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_int_schar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_int_schar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_int_uchar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_int_uchar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_int_short(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_int_short(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_int_int(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_int_int(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_int_long(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_int_long(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_int_float(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_int_float(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_int_double(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_int_double(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_float_schar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_float_schar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_float_uchar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_float_uchar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_float_short(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_float_short(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_float_int(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_float_int(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_float_long(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_float_long(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_float_float(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_float_float(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_float_double(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_float_double(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_double_schar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_double_schar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_double_uchar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_double_uchar(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_double_short(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_double_short(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_double_int(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_double_int(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_double_long(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_double_long(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_double_float(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_double_float(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCvx_double_double(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nput = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, RGN_WRITE, &xp); if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_putn_double_double(&xp, nput, value); if(lstatus != NC_NOERR && status == NC_NOERR) { /* not fatal to the loop */ status = lstatus; } (void) ncp->nciop->rel(ncp->nciop, offset, RGN_MODIFIED); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nput; } return status; } static int putNCv_text(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const char *value) { if(varp->type != NC_CHAR) return NC_ECHAR; return putNCvx_char_char(ncp, varp, start, nelems, value); } static int putNCv_schar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const schar *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_schar(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_schar(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_schar(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_schar(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_schar(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int putNCv_uchar(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const uchar *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_uchar(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_uchar(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_uchar(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_uchar(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_uchar(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int putNCv_short(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const short *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_short(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_short(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_short(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_short(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_short(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int putNCv_int(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const int *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_int(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_int(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_int(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_int(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_int(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int putNCv_long(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const long *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_long(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_long(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_long(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_long(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_long(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int putNCv_float(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const float *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_float(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_float(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_float(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_float(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_float(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int putNCv_double(NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, const double *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return putNCvx_schar_double(ncp, varp, start, nelems, value); case NC_SHORT: return putNCvx_short_double(ncp, varp, start, nelems, value); case NC_INT: return putNCvx_int_double(ncp, varp, start, nelems, value); case NC_FLOAT: return putNCvx_float_double(ncp, varp, start, nelems, value); case NC_DOUBLE: return putNCvx_double_double(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCvx_char_char(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, char *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_char_char(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_schar_schar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_schar_schar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_schar_uchar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_schar_uchar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_schar_short(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_schar_short(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_schar_int(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_schar_int(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_schar_long(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_schar_long(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_schar_float(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_schar_float(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_schar_double(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_schar_double(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_short_schar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_short_schar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_short_uchar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_short_uchar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_short_short(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_short_short(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_short_int(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_short_int(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_short_long(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_short_long(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_short_float(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_short_float(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_short_double(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_short_double(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_int_schar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_int_schar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_int_uchar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_int_uchar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_int_short(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_int_short(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_int_int(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_int_int(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_int_long(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_int_long(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_int_float(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_int_float(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_int_double(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_int_double(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_float_schar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_float_schar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_float_uchar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_float_uchar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_float_short(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_float_short(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_float_int(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_float_int(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_float_long(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_float_long(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_float_float(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_float_float(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_float_double(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_float_double(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_double_schar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, schar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_double_schar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_double_uchar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, uchar *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_double_uchar(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_double_short(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, short *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_double_short(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_double_int(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, int *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_double_int(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_double_long(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, long *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_double_long(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_double_float(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, float *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_double_float(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCvx_double_double(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, double *value) { off_t offset = NC_varoffset(ncp, varp, start); size_t remaining = varp->xsz * nelems; int status = NC_NOERR; const void *xp; if(nelems == 0) return NC_NOERR; assert(value != NULL); for(;;) { size_t extent = MIN(remaining, ncp->chunk); size_t nget = ncx_howmany(varp->type, extent); int lstatus = ncp->nciop->get(ncp->nciop, offset, extent, 0, (void **)&xp); /* cast away const */ if(lstatus != NC_NOERR) return lstatus; lstatus = ncx_getn_double_double(&xp, nget, value); if(lstatus != NC_NOERR && status == NC_NOERR) status = lstatus; (void) ncp->nciop->rel(ncp->nciop, offset, 0); remaining -= extent; if(remaining == 0) break; /* normal loop exit */ offset += extent; value += nget; } return status; } static int getNCv_schar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, schar *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_schar(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_schar(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_schar(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_schar(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_schar(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCv_uchar(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, uchar *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_uchar(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_uchar(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_uchar(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_uchar(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_uchar(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCv_short(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, short *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_short(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_short(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_short(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_short(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_short(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCv_int(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, int *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_int(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_int(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_int(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_int(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_int(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCv_long(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, long *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_long(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_long(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_long(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_long(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_long(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCv_float(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, float *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_float(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_float(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_float(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_float(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_float(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCv_double(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, double *value) { switch(varp->type){ case NC_CHAR: return NC_ECHAR; case NC_BYTE: return getNCvx_schar_double(ncp, varp, start, nelems, value); case NC_SHORT: return getNCvx_short_double(ncp, varp, start, nelems, value); case NC_INT: return getNCvx_int_double(ncp, varp, start, nelems, value); case NC_FLOAT: return getNCvx_float_double(ncp, varp, start, nelems, value); case NC_DOUBLE: return getNCvx_double_double(ncp, varp, start, nelems, value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } static int getNCv_text(const NC *ncp, const NC_var *varp, const size_t *start, size_t nelems, char *value) { if(varp->type != NC_CHAR) return NC_ECHAR; return getNCvx_char_char(ncp, varp, start, nelems, value); } /* * Copy 'nbytes' contiguous external values * from ('inncp', invp', inncoord') * to ('outncp', 'outvp', 'outcoord') * 'inncp' shouldn't be the same as 'outncp'. * Used only by ncvarcopy() */ static int NCxvarcpy(NC *inncp, NC_var *invp, size_t *incoord, NC *outncp, NC_var *outvp, size_t *outcoord, size_t nbytes) { int status; off_t inoffset = NC_varoffset(inncp, invp, incoord); off_t outoffset = NC_varoffset(outncp, outvp, outcoord); void *inxp; void *outxp; const size_t chunk = MIN(inncp->chunk, outncp->chunk); do { const size_t extent = MIN(nbytes, chunk); status = inncp->nciop->get(inncp->nciop, inoffset, extent, 0, &inxp); if(status != NC_NOERR) return status; status = outncp->nciop->get(outncp->nciop, outoffset, extent, RGN_WRITE, &outxp); if(status != NC_NOERR) { (void) inncp->nciop->rel(inncp->nciop, inoffset, 0); break; } (void) memcpy(outxp, inxp, extent); status = outncp->nciop->rel(outncp->nciop, outoffset, RGN_MODIFIED); (void) inncp->nciop->rel(inncp->nciop, inoffset, 0); nbytes -= extent; if(nbytes == 0) break; /* normal loop exit */ inoffset += extent; outoffset += extent; } while (status == NC_NOERR); return status; } /* * For ncvar{put,get}, * find the largest contiguous block from within 'edges'. * returns the index to the left of this (which may be -1). * Compute the number of contiguous elements and return * that in *iocountp. * The presence of "record" variables makes this routine * overly subtle. */ static int NCiocount(const NC *const ncp, const NC_var *const varp, const size_t *const edges, size_t *const iocountp) { const size_t *edp0 = edges; const size_t *edp = edges + varp->ndims; const size_t *shp = varp->shape + varp->ndims; if(IS_RECVAR(varp)) { if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only 'record' variable */ *iocountp = *edges; return(0); } /* else */ edp0++; } assert(edges != NULL); /* find max contiguous */ while(edp > edp0) { shp--; edp--; if(*edp < *shp ) { const size_t *zedp = edp; while(zedp >= edp0) { if(*zedp == 0) { *iocountp = 0; goto done; } /* Tip of the hat to segmented architectures */ if(zedp == edp0) break; zedp--; } break; } assert(*edp == *shp); } /* * edp, shp reference rightmost index s.t. *(edp +1) == *(shp +1) * * Or there is only one dimension. * If there is only one dimension and it is 'non record' dimension, * edp is &edges[0] and we will return -1. * If there is only one dimension and and it is a "record dimension", * edp is &edges[1] (out of bounds) and we will return 0; */ assert(shp >= varp->shape + varp->ndims -1 || *(edp +1) == *(shp +1)); /* now accumulate max count for a single io operation */ for(*iocountp = 1, edp0 = edp; edp0 < edges + varp->ndims; edp0++) { *iocountp *= *edp0; } done: return((int)(edp - edges) - 1); } /* * Set the elements of the array 'upp' to * the sum of the corresponding elements of * 'stp' and 'edp'. 'end' should be &stp[nelems]. */ static void set_upper(size_t *upp, /* modified on return */ const size_t *stp, const size_t *edp, const size_t *const end) { while(upp < end) { *upp++ = *stp++ + *edp++; } } /* * The infamous and oft-discussed odometer code. * * 'start[]' is the starting coordinate. * 'upper[]' is the upper bound s.t. start[ii] < upper[ii]. * 'coord[]' is the register, the current coordinate value. * For some ii, * upp == &upper[ii] * cdp == &coord[ii] * * Running this routine increments *cdp. * * If after the increment, *cdp is equal to *upp * (and cdp is not the leftmost dimension), * *cdp is "zeroed" to the starting value and * we need to "carry", eg, increment one place to * the left. * * TODO: Some architectures hate recursion? * Reimplement non-recursively. */ static void odo1(const size_t *const start, const size_t *const upper, size_t *const coord, /* modified on return */ const size_t *upp, size_t *cdp) { assert(coord <= cdp && cdp <= coord + NC_MAX_VAR_DIMS); assert(upper <= upp && upp <= upper + NC_MAX_VAR_DIMS); assert(upp - upper == cdp - coord); assert(*cdp <= *upp); (*cdp)++; if(cdp != coord && *cdp >= *upp) { *cdp = start[cdp - coord]; odo1(start, upper, coord, upp -1, cdp -1); } } #ifdef _CRAYC #pragma _CRI noinline odo1 #endif /* Public */ int nc_put_var1_text(int ncid, int varid, const size_t *coord, const char *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type != NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_text(ncp, varp, coord, 1, value); } int nc_put_var1_uchar(int ncid, int varid, const size_t *coord, const uchar *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_uchar(ncp, varp, coord, 1, value); } int nc_put_var1_schar(int ncid, int varid, const size_t *coord, const schar *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_schar(ncp, varp, coord, 1, value); } int nc_put_var1_short(int ncid, int varid, const size_t *coord, const short *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_short(ncp, varp, coord, 1, value); } int nc_put_var1_int(int ncid, int varid, const size_t *coord, const int *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_int(ncp, varp, coord, 1, value); } int nc_put_var1_long(int ncid, int varid, const size_t *coord, const long *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_long(ncp, varp, coord, 1, value); } int nc_put_var1_float(int ncid, int varid, const size_t *coord, const float *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_float(ncp, varp, coord, 1, value); } int nc_put_var1_double(int ncid, int varid, const size_t *coord, const double *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *coord +1); if(status != NC_NOERR) return status; } return putNCv_double(ncp, varp, coord, 1, value); } int nc_get_var1_text(int ncid, int varid, const size_t *coord, char *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type != NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_text(ncp, varp, coord, 1, value); } int nc_get_var1_uchar(int ncid, int varid, const size_t *coord, uchar *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_uchar(ncp, varp, coord, 1, value); } int nc_get_var1_schar(int ncid, int varid, const size_t *coord, schar *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_schar(ncp, varp, coord, 1, value); } int nc_get_var1_short(int ncid, int varid, const size_t *coord, short *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_short(ncp, varp, coord, 1, value); } int nc_get_var1_int(int ncid, int varid, const size_t *coord, int *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_int(ncp, varp, coord, 1, value); } int nc_get_var1_long(int ncid, int varid, const size_t *coord, long *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_long(ncp, varp, coord, 1, value); } int nc_get_var1_float(int ncid, int varid, const size_t *coord, float *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_float(ncp, varp, coord, 1, value); } int nc_get_var1_double(int ncid, int varid, const size_t *coord, double *value) { int status; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, coord); if(status != NC_NOERR) return status; return getNCv_double(ncp, varp, coord, 1, value); } int nc_put_vara_text(int ncid, int varid, const size_t *start, const size_t *edges, const char *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type != NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_text(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_text(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_text(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_text(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_put_vara_uchar(int ncid, int varid, const size_t *start, const size_t *edges, const uchar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_uchar(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_uchar(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_uchar(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_uchar(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_put_vara_schar(int ncid, int varid, const size_t *start, const size_t *edges, const schar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_schar(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_schar(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_schar(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_schar(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_put_vara_short(int ncid, int varid, const size_t *start, const size_t *edges, const short *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_short(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_short(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_short(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_short(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_put_vara_int(int ncid, int varid, const size_t *start, const size_t *edges, const int *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_int(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_int(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_int(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_int(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_put_vara_long(int ncid, int varid, const size_t *start, const size_t *edges, const long *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_long(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_long(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_long(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_long(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_put_vara_float(int ncid, int varid, const size_t *start, const size_t *edges, const float *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_float(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_float(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_float(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_float(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_put_vara_double(int ncid, int varid, const size_t *start, const size_t *edges, const double *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( putNCv_double(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { status = NCvnrecs(ncp, *start + *edges); if(status != NC_NOERR) return status; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( putNCv_double(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( putNCv_double(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = putNCv_double(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_text(int ncid, int varid, const size_t *start, const size_t *edges, char *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type != NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_text(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_text(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_text(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_text(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_uchar(int ncid, int varid, const size_t *start, const size_t *edges, uchar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_uchar(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_uchar(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_uchar(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_uchar(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_schar(int ncid, int varid, const size_t *start, const size_t *edges, schar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_schar(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_schar(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_schar(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_schar(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_short(int ncid, int varid, const size_t *start, const size_t *edges, short *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_short(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_short(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_short(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_short(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_int(int ncid, int varid, const size_t *start, const size_t *edges, int *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_int(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_int(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_int(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_int(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_long(int ncid, int varid, const size_t *start, const size_t *edges, long *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_long(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_long(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_long(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_long(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_float(int ncid, int varid, const size_t *start, const size_t *edges, float *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_float(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_float(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_float(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_float(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } int nc_get_vara_double(int ncid, int varid, const size_t *start, const size_t *edges, double *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; int ii; size_t iocount; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; status = NCcoordck(ncp, varp, start); if(status != NC_NOERR) return status; status = NCedgeck(ncp, varp, start, edges); if(status != NC_NOERR) return status; if(varp->ndims == 0) /* scalar variable */ { return( getNCv_double(ncp, varp, start, 1, value) ); } if(IS_RECVAR(varp)) { if(*start + *edges > NC_get_numrecs(ncp)) return NC_EEDGE; if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return( getNCv_double(ncp, varp, start, *edges, value) ); } } /* * find max contiguous * and accumulate max count for a single io operation */ ii = NCiocount(ncp, varp, edges, &iocount); if(ii == -1) { return( getNCv_double(ncp, varp, start, iocount, value) ); } assert(ii >= 0); { /* inline */ ALLOC_ONSTACK(coord, size_t, varp->ndims); ALLOC_ONSTACK(upper, size_t, varp->ndims); const size_t index2 = ii; /* copy in starting indices */ (void) memcpy(coord, start, varp->ndims * sizeof(size_t)); /* set up in maximum indices */ set_upper(upper, start, edges, &upper[varp->ndims]); /* ripple counter */ while(*coord < *upper) { const int lstatus = getNCv_double(ncp, varp, coord, iocount, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += iocount; odo1(start, upper, coord, &upper[index2], &coord[index2]); } FREE_ONSTACK(upper); FREE_ONSTACK(coord); } /* end inline */ return status; } #if defined(__cplusplus) /* C++ consts default to internal linkage and must be initialized */ const size_t coord_zero[NC_MAX_VAR_DIMS] = {0}; #else # if defined(_MSC_VER) && _MSC_VER >= 1300 static const size_t coord_zero[NC_MAX_VAR_DIMS] = { 0 }; # else static const size_t coord_zero[NC_MAX_VAR_DIMS]; # endif #endif int nc_put_var_text(int ncid, int varid, const char *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type != NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_text(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_text(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_text(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_text(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_put_var_uchar(int ncid, int varid, const uchar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_uchar(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_uchar(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_uchar(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_uchar(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_put_var_schar(int ncid, int varid, const schar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_schar(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_schar(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_schar(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_schar(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_put_var_short(int ncid, int varid, const short *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_short(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_short(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_short(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_short(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_put_var_int(int ncid, int varid, const int *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_int(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_int(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_int(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_int(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_put_var_long(int ncid, int varid, const long *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_long(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_long(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_long(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_long(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_put_var_float(int ncid, int varid, const float *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_float(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_float(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_float(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_float(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_put_var_double(int ncid, int varid, const double *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->type == NC_CHAR) return NC_ECHAR; if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( putNCv_double(ncp, varp, &zed, 1, value) ); } if(!IS_RECVAR(varp)) { return(putNCv_double(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(putNCv_double(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = putNCv_double(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_text(int ncid, int varid, char *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_text(ncp, varp, &zed, 1, value) ); } if(varp->type != NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_text(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_text(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_text(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_uchar(int ncid, int varid, uchar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_uchar(ncp, varp, &zed, 1, value) ); } if(varp->type == NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_uchar(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_uchar(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_uchar(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_schar(int ncid, int varid, schar *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_schar(ncp, varp, &zed, 1, value) ); } if(varp->type == NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_schar(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_schar(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_schar(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_short(int ncid, int varid, short *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_short(ncp, varp, &zed, 1, value) ); } if(varp->type == NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_short(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_short(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_short(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_int(int ncid, int varid, int *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_int(ncp, varp, &zed, 1, value) ); } if(varp->type == NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_int(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_int(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_int(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_long(int ncid, int varid, long *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_long(ncp, varp, &zed, 1, value) ); } if(varp->type == NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_long(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_long(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_long(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_float(int ncid, int varid, float *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_float(ncp, varp, &zed, 1, value) ); } if(varp->type == NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_float(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_float(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_float(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } int nc_get_var_double(int ncid, int varid, double *value) { int status = NC_NOERR; NC *ncp; const NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_indef(ncp)) return NC_EINDEFINE; varp = NC_lookupvar(ncp, varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: lost NC_EGLOBAL */ if(varp->ndims == 0) /* scalar variable */ { const size_t zed = 0; return( getNCv_double(ncp, varp, &zed, 1, value) ); } if(varp->type == NC_CHAR) return NC_ECHAR; if(!IS_RECVAR(varp)) { return(getNCv_double(ncp, varp, coord_zero, *varp->dsizes, value)); } /* else */ if(varp->ndims == 1 && ncp->recsize <= varp->len) { /* one dimensional && the only record variable */ return(getNCv_double(ncp, varp, coord_zero, NC_get_numrecs(ncp), value)); } /* else */ { ALLOC_ONSTACK(coord, size_t, varp->ndims); size_t elemsPerRec = 1; const size_t nrecs = NC_get_numrecs(ncp); (void) memset(coord, 0, varp->ndims * sizeof(size_t)); /* TODO: fix dsizes to avoid this nonsense */ if(varp->ndims > 1) elemsPerRec = varp->dsizes[1]; while(*coord < nrecs) { const int lstatus = getNCv_double(ncp, varp, coord, elemsPerRec, value); if(lstatus != NC_NOERR) { if(lstatus != NC_ERANGE) { status = lstatus; /* fatal for the loop */ break; } /* else NC_ERANGE, not fatal for the loop */ if(status == NC_NOERR) status = lstatus; } value += elemsPerRec; (*coord)++; } FREE_ONSTACK(coord); } /* elemsPerRec */ return status; } /* Begin putgetg.c */ int nc_get_vars_text ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, char *value) { return nc_get_varm_text (ncid, varid, start, edges, stride, 0, value); } int nc_get_vars_uchar ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, uchar *value) { return nc_get_varm_uchar (ncid, varid, start, edges, stride, 0, value); } int nc_get_vars_schar ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, schar *value) { return nc_get_varm_schar (ncid, varid, start, edges, stride, 0, value); } int nc_get_vars_short ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, short *value) { return nc_get_varm_short (ncid, varid, start, edges, stride, 0, value); } int nc_get_vars_int ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, int *value) { return nc_get_varm_int (ncid, varid, start, edges, stride, 0, value); } int nc_get_vars_long ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, long *value) { return nc_get_varm_long (ncid, varid, start, edges, stride, 0, value); } int nc_get_vars_float ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, float *value) { return nc_get_varm_float (ncid, varid, start, edges, stride, 0, value); } int nc_get_vars_double ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, double *value) { return nc_get_varm_double (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_text ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const char *value) { return nc_put_varm_text (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_uchar ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const uchar *value) { return nc_put_varm_uchar (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_schar ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const schar *value) { return nc_put_varm_schar (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_short ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const short *value) { return nc_put_varm_short (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_int ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const int *value) { return nc_put_varm_int (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_long ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const long *value) { return nc_put_varm_long (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_float ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const float *value) { return nc_put_varm_float (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars_double ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const double *value) { return nc_put_varm_double (ncid, varid, start, edges, stride, 0, value); } /* * Generalized hyperslab input. */ int nc_get_varm_text(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, char *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type != NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_text (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_text() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_text (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_get_varm_uchar(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, uchar *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_uchar (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_uchar() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_uchar (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_get_varm_schar(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, schar *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_schar (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_schar() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_schar (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_get_varm_short(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, short *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_short (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_short() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_short (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_get_varm_int(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, int *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_int (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_int() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_int (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_get_varm_long(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, long *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_long (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_long() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_long (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_get_varm_float(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, float *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_float (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_float() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_float (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_get_varm_double(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, double *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return getNCv_double (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = maxidim; idim >= 0; --idim) { size_t dimlen = idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) : varp->shape[idim]; if (mystart[idim] >= dimlen) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > dimlen) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_get_vara_double() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_get_vara_double (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } #ifdef NO_NETCDF_2 extern int nctypelen(nc_type datatype); #endif /* * Generalized hyperslab output. */ int nc_put_varm_text(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const char *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type != NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_text (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_text() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_text (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_put_varm_uchar(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const uchar *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_uchar (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_uchar() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_uchar (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_put_varm_schar(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const schar *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_schar (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_schar() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_schar (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_put_varm_short(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const short *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_short (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_short() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_short (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_put_varm_int(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const int *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_int (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_int() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_int (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_put_varm_long(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const long *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_long (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_long() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_long (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_put_varm_float(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const float *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_float (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_float() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_float (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } int nc_put_varm_double(int ncid, int varid, const size_t *start, const size_t *edges, const ptrdiff_t *stride, const ptrdiff_t *map, const double *value) { int status = ENOERR; NC *ncp; NC_var *varp; int maxidim; /* maximum dimensional index */ status = NC_check_id (ncid, &ncp); if (status != NC_NOERR) return status; if (NC_indef (ncp)) { return NC_EINDEFINE; } if (NC_readonly (ncp)) return NC_EPERM; varp = NC_lookupvar (ncp, varid); if (varp == NULL) return NC_ENOTVAR; if(varp->type == NC_CHAR) return NC_ECHAR; maxidim = (int) varp->ndims - 1; if (maxidim < 0) { /* * The variable is a scalar; consequently, * there s only one thing to get and only one place to put it. * (Why was I called?) */ return putNCv_double (ncp, varp, start, 1, value); } /* * else * The variable is an array. */ { int idim; size_t *mystart = NULL; size_t *myedges; size_t *iocount; /* count vector */ size_t *stop; /* stop indexes */ size_t *length; /* edge lengths in bytes */ ptrdiff_t *mystride; ptrdiff_t *mymap; /* * Verify stride argument. */ for (idim = 0; idim <= maxidim; ++idim) { if (stride != NULL && (stride[idim] == 0 /* cast needed for braindead systems with signed size_t */ || (unsigned long) stride[idim] >= X_INT_MAX)) { return NC_ESTRIDE; } } /* assert(sizeof(ptrdiff_t) >= sizeof(size_t)); */ mystart = (size_t *)calloc(varp->ndims * 7, sizeof(ptrdiff_t)); if(mystart == NULL) return NC_ENOMEM; myedges = mystart + varp->ndims; iocount = myedges + varp->ndims; stop = iocount + varp->ndims; length = stop + varp->ndims; mystride = (ptrdiff_t *)(length + varp->ndims); mymap = mystride + varp->ndims; /* * Initialize I/O parameters. */ for (idim = maxidim; idim >= 0; --idim) { mystart[idim] = start != NULL ? start[idim] : 0; if (edges[idim] == 0) { status = NC_NOERR; /* read/write no data */ goto done; } myedges[idim] = edges != NULL ? edges[idim] : idim == 0 && IS_RECVAR (varp) ? NC_get_numrecs(ncp) - mystart[idim] : varp->shape[idim] - mystart[idim]; mystride[idim] = stride != NULL ? stride[idim] : 1; mymap[idim] = map != NULL ? map[idim] : idim == maxidim ? 1 : mymap[idim + 1] * (ptrdiff_t) myedges[idim + 1]; iocount[idim] = 1; length[idim] = mymap[idim] * myedges[idim]; stop[idim] = mystart[idim] + myedges[idim] * mystride[idim]; } /* * Check start, edges */ for (idim = IS_RECVAR (varp); idim < maxidim; ++idim) { if (mystart[idim] > varp->shape[idim]) { status = NC_EINVALCOORDS; goto done; } if (mystart[idim] + myedges[idim] > varp->shape[idim]) { status = NC_EEDGE; goto done; } } /* * As an optimization, adjust I/O parameters when the fastest * dimension has unity stride both externally and internally. * In this case, the user could have called a simpler routine * (i.e. ncvarnc_put_vara_double() */ if (mystride[maxidim] == 1 && mymap[maxidim] == 1) { iocount[maxidim] = myedges[maxidim]; mystride[maxidim] = (ptrdiff_t) myedges[maxidim]; mymap[maxidim] = (ptrdiff_t) length[maxidim]; } /* * Perform I/O. Exit when done. */ for (;;) { /* TODO: */ int lstatus = nc_put_vara_double (ncid, varid, mystart, iocount, value); if (lstatus != NC_NOERR && (status == NC_NOERR || lstatus != NC_ERANGE)) status = lstatus; /* * The following code permutes through the variable s * external start-index space and it s internal address * space. At the UPC, this algorithm is commonly * called "odometer code". */ idim = maxidim; carry: value += mymap[idim]; mystart[idim] += mystride[idim]; if (mystart[idim] == stop[idim]) { mystart[idim] = start[idim]; value -= length[idim]; if (--idim < 0) break; /* normal return */ goto carry; } } /* I/O loop */ done: free(mystart); } /* variable is array */ return status; } /* * Copy the values of a variable from an input netCDF to an output netCDF. * Input and output var assummed to have the same shape. * return -1 on error. */ int nc_copy_var(int ncid_in, int varid, int ncid_out) { int status = NC_NOERR; NC *inncp, *outncp; NC_var *invp, *outvp; status = NC_check_id(ncid_in, &inncp); if(status != NC_NOERR) return status; if(NC_indef(inncp)) { return NC_EINDEFINE; } status = NC_check_id(ncid_out, &outncp); if(status != NC_NOERR) return status; if(NC_readonly(outncp)) { /* output file isn't writable */ return NC_EPERM; } if(NC_indef(outncp)) { return NC_EINDEFINE; } /* find the variable in the input cdf */ invp = NC_lookupvar(inncp, varid); if(invp == NULL) { return NC_ENOTVAR; } /* find the variable in the output cdf */ if(NC_findvar(&outncp->vars, invp->name->cp, &outvp) == -1) { return NC_ENOTVAR; } /* can we even attempt to copy without conversion? */ if(outvp->type != invp->type) { return NC_EINVAL; } if( (invp->ndims == 0 && outvp->ndims != 0) || (invp->ndims != 0 && outvp->ndims == 0) || (IS_RECVAR(invp) && !IS_RECVAR(outvp)) || (!IS_RECVAR(invp) && IS_RECVAR(outvp)) || (invp->len != outvp->len) ) { return NC_EINVAL; } /* * Check coordinates */ { ALLOC_ONSTACK(coord, size_t, invp->ndims); const size_t nrecs = NC_get_numrecs(inncp); (void) memcpy(coord, invp->shape, invp->ndims * sizeof(size_t)); if(IS_RECVAR(invp)) *coord = nrecs; { size_t ii = 0; for(; ii < invp->ndims; ii++) coord[ii] --; } /* at this point, coord is the largest valid coord of invp */ if(NCcoordck(outncp, outvp, coord) != NC_NOERR) { return NC_EINVAL; } /* else */ (void) memset(coord, 0, invp->ndims * sizeof(size_t)); if(!IS_RECVAR(invp)) { status = NCxvarcpy(inncp, invp, coord, outncp, outvp, coord, invp->len); goto done; } /* else */ status = NCvnrecs(outncp, nrecs); if(status != NC_NOERR) goto done; for( /*NADA*/; *coord < nrecs; (*coord)++) { status = NCxvarcpy(inncp, invp, coord, outncp, outvp, coord, invp->len); if(status != NC_NOERR) break; } done: FREE_ONSTACK(coord); } return status; } /* no longer deprecated, used to support the 2.x interface and also the netcdf-4 api. */ int nc_get_att(int ncid, int varid, const char *name, void *value) { int status; nc_type atttype; status = nc_inq_atttype(ncid, varid, name, &atttype); if(status != NC_NOERR) return status; switch (atttype) { case NC_BYTE: return nc_get_att_schar(ncid, varid, name, (schar *)value); case NC_CHAR: return nc_get_att_text(ncid, varid, name, (char *)value); case NC_SHORT: return nc_get_att_short(ncid, varid, name, (short *)value); case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) return nc_get_att_int(ncid, varid, name, (int *)value); #elif SIZEOF_LONG == X_SIZEOF_INT return nc_get_att_long(ncid, varid, name, (long *)value); #endif case NC_FLOAT: return nc_get_att_float(ncid, varid, name, (float *)value); case NC_DOUBLE: return nc_get_att_double(ncid, varid, name, (double *)value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_put_att( int ncid, int varid, const char *name, nc_type type, size_t nelems, const void *value) { switch (type) { case NC_BYTE: return nc_put_att_schar(ncid, varid, name, type, nelems, (schar *)value); case NC_CHAR: return nc_put_att_text(ncid, varid, name, nelems, (char *)value); case NC_SHORT: return nc_put_att_short(ncid, varid, name, type, nelems, (short *)value); case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) return nc_put_att_int(ncid, varid, name, type, nelems, (int *)value); #elif SIZEOF_LONG == X_SIZEOF_INT return nc_put_att_long(ncid, varid, name, type, nelems, (long *)value); #endif case NC_FLOAT: return nc_put_att_float(ncid, varid, name, type, nelems, (float *)value); case NC_DOUBLE: return nc_put_att_double(ncid, varid, name, type, nelems, (double *)value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_get_var1(int ncid, int varid, const size_t *coord, void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_get_var1_text(ncid, varid, coord, (char *) value); case NC_BYTE: return nc_get_var1_schar(ncid, varid, coord, (schar *) value); case NC_SHORT: return nc_get_var1_short(ncid, varid, coord, (short *) value); case NC_INT: return nc_get_var1_int(ncid, varid, coord, (int *) value); case NC_FLOAT: return nc_get_var1_float(ncid, varid, coord, (float *) value); case NC_DOUBLE: return nc_get_var1_double(ncid, varid, coord, (double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_put_var1(int ncid, int varid, const size_t *coord, const void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_put_var1_text(ncid, varid, coord, (const char *) value); case NC_BYTE: return nc_put_var1_schar(ncid, varid, coord, (const schar *) value); case NC_SHORT: return nc_put_var1_short(ncid, varid, coord, (const short *) value); case NC_INT: return nc_put_var1_int(ncid, varid, coord, (const int *) value); case NC_FLOAT: return nc_put_var1_float(ncid, varid, coord, (const float *) value); case NC_DOUBLE: return nc_put_var1_double(ncid, varid, coord, (const double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_get_vara(int ncid, int varid, const size_t *start, const size_t *edges, void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_get_vara_text(ncid, varid, start, edges, (char *) value); case NC_BYTE: return nc_get_vara_schar(ncid, varid, start, edges, (schar *) value); case NC_SHORT: return nc_get_vara_short(ncid, varid, start, edges, (short *) value); case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) return nc_get_vara_int(ncid, varid, start, edges, (int *) value); #elif SIZEOF_LONG == X_SIZEOF_INT return nc_get_vara_long(ncid, varid, start, edges, (long *) value); #else #error "nc_get_vara implementation" #endif case NC_FLOAT: return nc_get_vara_float(ncid, varid, start, edges, (float *) value); case NC_DOUBLE: return nc_get_vara_double(ncid, varid, start, edges, (double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_put_vara(int ncid, int varid, const size_t *start, const size_t *edges, const void *value) { int status; nc_type vartype; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; switch(vartype){ case NC_CHAR: return nc_put_vara_text(ncid, varid, start, edges, (const char *) value); case NC_BYTE: return nc_put_vara_schar(ncid, varid, start, edges, (const schar *) value); case NC_SHORT: return nc_put_vara_short(ncid, varid, start, edges, (const short *) value); case NC_INT: return nc_put_vara_int(ncid, varid, start, edges, (const int *) value); case NC_FLOAT: return nc_put_vara_float(ncid, varid, start, edges, (const float *) value); case NC_DOUBLE: return nc_put_vara_double(ncid, varid, start, edges, (const double *) value); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } return NC_EBADTYPE; } int nc_get_varm ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const ptrdiff_t * imapp, void *value) { int status; nc_type vartype; int varndims; ptrdiff_t *cvtmap = NULL; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; status = nc_inq_varndims(ncid, varid, &varndims); if(status != NC_NOERR) return status; if(imapp != NULL && varndims != 0) { /* * convert map units from bytes to units of sizeof(type) */ size_t ii; const ptrdiff_t szof = (ptrdiff_t) nctypelen(vartype); cvtmap = (ptrdiff_t *)calloc(varndims, sizeof(ptrdiff_t)); if(cvtmap == NULL) return NC_ENOMEM; for(ii = 0; (int)ii < varndims; ii++) { if(imapp[ii] % szof != 0) { free(cvtmap); return NC_EINVAL; } cvtmap[ii] = imapp[ii] / szof; } imapp = cvtmap; } switch(vartype){ case NC_CHAR: status = nc_get_varm_text(ncid, varid, start, edges, stride, imapp, (char *) value); break; case NC_BYTE: status = nc_get_varm_schar(ncid, varid, start, edges, stride, imapp, (schar *) value); break; case NC_SHORT: status = nc_get_varm_short(ncid, varid, start, edges, stride, imapp, (short *) value); break; case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) status = nc_get_varm_int(ncid, varid, start, edges, stride, imapp, (int *) value); #elif SIZEOF_LONG == X_SIZEOF_INT status = nc_get_varm_long(ncid, varid, start, edges, stride, imapp, (long *) value); #else #error "nc_get_varm implementation" #endif break; case NC_FLOAT: status = nc_get_varm_float(ncid, varid, start, edges, stride, imapp, (float *) value); break; case NC_DOUBLE: status = nc_get_varm_double(ncid, varid, start, edges, stride, imapp, (double *) value); break; default: status = NC_EBADTYPE; break; } if(cvtmap != NULL) { free(cvtmap); } return status; } int nc_put_varm ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const ptrdiff_t * imapp, const void *value) { int status; nc_type vartype; int varndims; ptrdiff_t *cvtmap = NULL; status = nc_inq_vartype(ncid, varid, &vartype); if(status != NC_NOERR) return status; status = nc_inq_varndims(ncid, varid, &varndims); if(status != NC_NOERR) return status; if(imapp != NULL && varndims != 0) { /* * convert map units from bytes to units of sizeof(type) */ size_t ii; const ptrdiff_t szof = (ptrdiff_t) nctypelen(vartype); cvtmap = (ptrdiff_t *)calloc(varndims, sizeof(ptrdiff_t)); if(cvtmap == NULL) return NC_ENOMEM; for(ii = 0; (int)ii < varndims; ii++) { if(imapp[ii] % szof != 0) { free(cvtmap); return NC_EINVAL; } cvtmap[ii] = imapp[ii] / szof; } imapp = cvtmap; } switch(vartype){ case NC_CHAR: status = nc_put_varm_text(ncid, varid, start, edges, stride, imapp, (const char *) value); break; case NC_BYTE: status = nc_put_varm_schar(ncid, varid, start, edges, stride, imapp, (const schar *) value); break; case NC_SHORT: status = nc_put_varm_short(ncid, varid, start, edges, stride, imapp, (const short *) value); break; case NC_INT: #if (SIZEOF_INT >= X_SIZEOF_INT) status = nc_put_varm_int(ncid, varid, start, edges, stride, imapp, (const int *) value); #elif SIZEOF_LONG == X_SIZEOF_INT status = nc_put_varm_long(ncid, varid, start, edges, stride, imapp, (const long *) value); #else #error "nc_put_varm implementation" #endif break; case NC_FLOAT: status = nc_put_varm_float(ncid, varid, start, edges, stride, imapp, (const float *) value); break; case NC_DOUBLE: status = nc_put_varm_double(ncid, varid, start, edges, stride, imapp, (const double *) value); break; default: status = NC_EBADTYPE; break; } if(cvtmap != NULL) { free(cvtmap); } return status; } int nc_get_vars ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, void *value) { return nc_get_varm (ncid, varid, start, edges, stride, 0, value); } int nc_put_vars ( int ncid, int varid, const size_t * start, const size_t * edges, const ptrdiff_t * stride, const void *value) { return nc_put_varm (ncid, varid, start, edges, stride, 0, value); } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/README.txt0000644000175000017500000000327411606020250022164 0ustar amckinstryamckinstryThis directory contains a subset of the NetCDF source code. Specifically, it is the "libsrc" directory of NetCDF, since VTK only requires the NetCDF library itself and not any utilities built on top of it. The only differences to the vendor's release are: - The README (as README.netcdf), RELEASE_NOTES, and COPYRIGHT files from the top level of the NetCDF source code are also included. - Tabs aren't allowed by VTK's CVS checkin scripts, so they have been converted to spaces. - some "index" parameters have been renamed to "index2" to avoid shadowing "index" BSD function. The head of the netcdf-release branch corresponds to the NetCDF 3.6.2 release. Instructions for updating to a new NetCDF release: 0. Go to a place where you can have some working directories: cd /tmp 1. Check out the netcdf-release branch cvs -d :pserver:anonymous@www.vtk.org:/cvsroot/VTK -z3 \ co -r netcdf-release VTK/Utilities/vtknetcdf 2. Download and unpack the latest netcdf release: wget ftp://ftp.unidata.ucar.edu/pub/netcdf/netcdf.tar.gz tar xzvf netcdf.tar.gz 3. Copy files from the netCDF distribution into the VTK NetCDF checkout and commit: cp netcdf-*/libsrc/* vtknetcdf cp netcdf-*/README vtknetcdf/README.netcdf cp netcdf-*/RELEASE_NOTES netcdf-*/COPYRIGHT vtknetcdf cd vtknetcdf cvs commit -m "ENH: A You will need to change tabs to spaces before committing. You may need to cvs add or cvs remove files to track the NetCDF distribution. 4. Now merge the changes into the trunk: cvs update -PAd cvs update -j netcdf-release 5. Take care of any conflicts. 6. Build, test, and commit 7. Listen to the dashboards for problems on other compilers/architectures. xdmf-2.1.dfsg.1/Utilities/vtknetcdf/var.c0000644000175000017500000003626411606020250021427 0ustar amckinstryamckinstry/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: var.c,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #include "nc.h" #include #include #include #include "ncx.h" #include "rnd.h" #if defined(_MSC_VER) && (_MSC_VER >= 1400) # pragma warning ( disable : 4130 ) /* logical operation on address of string constant */ #endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ /* * Free var * Formerly NC_free_var(var) */ void free_NC_var(NC_var *varp) { if(varp == NULL) return; free_NC_attrarrayV(&varp->attrs); free_NC_string(varp->name); free(varp); } /* * Common code for new_NC_var() * and ncx_get_NC_var() */ NC_var * new_x_NC_var( NC_string *strp, size_t ndims) { NC_var *varp; const size_t o1 = M_RNDUP(ndims * sizeof(int)); const size_t o2 = M_RNDUP(ndims * sizeof(size_t)); const size_t sz = M_RNDUP(sizeof(NC_var)) + o1 + o2 + ndims * sizeof(size_t); varp = (NC_var *) malloc(sz); if(varp == NULL ) return NULL; (void) memset(varp, 0, sz); varp->name = strp; varp->ndims = ndims; if(ndims != 0) { /* * NOTE: lint may complain about the next 3 lines: * "pointer cast may result in improper alignment". * We use the M_RNDUP() macro to get the proper alignment. */ varp->dimids = (int *)((char *)varp + M_RNDUP(sizeof(NC_var))); varp->shape = (size_t *)((char *)varp->dimids + o1); varp->dsizes = (size_t *)((char *)varp->shape + o2); } varp->xsz = 0; varp->len = 0; varp->begin = 0; return varp; } /* * Formerly NC_new_var() */ static NC_var * new_NC_var(const char *name, nc_type type, size_t ndims, const int *dimids) { NC_string *strp; NC_var *varp; strp = new_NC_string(strlen(name), name); if(strp == NULL) return NULL; varp = new_x_NC_var(strp, ndims); if(varp == NULL ) { free_NC_string(strp); return NULL; } varp->type = type; if( ndims != 0 && dimids != NULL) (void) memcpy(varp->dimids, dimids, ndims * sizeof(int)); return(varp); } static NC_var * dup_NC_var(const NC_var *rvarp) { NC_var *varp = new_NC_var(rvarp->name->cp, rvarp->type, rvarp->ndims, rvarp->dimids); if(varp == NULL) return NULL; if(dup_NC_attrarrayV(&varp->attrs, &rvarp->attrs) != NC_NOERR) { free_NC_var(varp); return NULL; } (void) memcpy(varp->shape, rvarp->shape, rvarp->ndims * sizeof(size_t)); (void) memcpy(varp->dsizes, rvarp->dsizes, rvarp->ndims * sizeof(size_t)); varp->xsz = rvarp->xsz; varp->len = rvarp->len; varp->begin = rvarp->begin; return varp; } /* vararray */ /* * Free the stuff "in" (referred to by) an NC_vararray. * Leaves the array itself allocated. */ void free_NC_vararrayV0(NC_vararray *ncap) { assert(ncap != NULL); if(ncap->nelems == 0) return; assert(ncap->value != NULL); { NC_var **vpp = ncap->value; NC_var *const *const end = &vpp[ncap->nelems]; for( /*NADA*/; vpp < end; vpp++) { free_NC_var(*vpp); *vpp = NULL; } } ncap->nelems = 0; } /* * Free NC_vararray values. * formerly NC_free_array() */ void free_NC_vararrayV(NC_vararray *ncap) { assert(ncap != NULL); if(ncap->nalloc == 0) return; assert(ncap->value != NULL); free_NC_vararrayV0(ncap); free(ncap->value); ncap->value = NULL; ncap->nalloc = 0; } int dup_NC_vararrayV(NC_vararray *ncap, const NC_vararray *ref) { int status = NC_NOERR; assert(ref != NULL); assert(ncap != NULL); if(ref->nelems != 0) { const size_t sz = ref->nelems * sizeof(NC_var *); ncap->value = (NC_var **) malloc(sz); if(ncap->value == NULL) return NC_ENOMEM; (void) memset(ncap->value, 0, sz); ncap->nalloc = ref->nelems; } ncap->nelems = 0; { NC_var **vpp = ncap->value; const NC_var **drpp = (const NC_var **)ref->value; NC_var *const *const end = &vpp[ref->nelems]; for( /*NADA*/; vpp < end; drpp++, vpp++, ncap->nelems++) { *vpp = dup_NC_var(*drpp); if(*vpp == NULL) { status = NC_ENOMEM; break; } } } if(status != NC_NOERR) { free_NC_vararrayV(ncap); return status; } assert(ncap->nelems == ref->nelems); return NC_NOERR; } /* * Add a new handle on the end of an array of handles * Formerly NC_incr_array(array, tail) */ static int incr_NC_vararray(NC_vararray *ncap, NC_var *newelemp) { NC_var **vp; assert(ncap != NULL); if(ncap->nalloc == 0) { assert(ncap->nelems == 0); vp = (NC_var **) malloc(NC_ARRAY_GROWBY * sizeof(NC_var *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc = NC_ARRAY_GROWBY; } else if(ncap->nelems +1 > ncap->nalloc) { vp = (NC_var **) realloc(ncap->value, (ncap->nalloc + NC_ARRAY_GROWBY) * sizeof(NC_var *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc += NC_ARRAY_GROWBY; } if(newelemp != NULL) { ncap->value[ncap->nelems] = newelemp; ncap->nelems++; } return NC_NOERR; } static NC_var * elem_NC_vararray(const NC_vararray *ncap, size_t elem) { assert(ncap != NULL); /* cast needed for braindead systems with signed size_t */ if(ncap->nelems == 0 || (unsigned long)elem >= ncap->nelems) return NULL; assert(ncap->value != NULL); return ncap->value[elem]; } /* End vararray per se */ /* * Step thru NC_VARIABLE array, seeking match on name. * Return varid or -1 on not found. * *varpp is set to the appropriate NC_var. * Formerly (sort of) NC_hvarid */ int NC_findvar(const NC_vararray *ncap, const char *name, NC_var **varpp) { NC_var **loc; size_t slen; int varid; assert(ncap != NULL); if(ncap->nelems == 0) return -1; loc = (NC_var **) ncap->value; slen = strlen(name); for(varid = 0; (size_t) varid < ncap->nelems; varid++, loc++) { /* NOTE: The [slen-1] check is a specific optimization for * exodusII files with many blocks and variables. Because * names usually end with a different suffix, check that * before comparing entire string. */ if(strlen((*loc)->name->cp) == slen && name[slen-1]==(*loc)->name->cp[slen-1] && strncmp((*loc)->name->cp, name, slen) == 0) { if(varpp != NULL) *varpp = *loc; return(varid); /* Normal return */ } } return(-1); /* not found */ } /* * For a netcdf type * return the size of one element in the external representation. * Note that arrays get rounded up to X_ALIGN boundaries. * Formerly NC_xtypelen * See also ncx_len() */ size_t ncx_szof(nc_type type) { switch(type){ case NC_BYTE: case NC_CHAR: return(1); case NC_SHORT : return(2); case NC_INT: return X_SIZEOF_INT; case NC_FLOAT: return X_SIZEOF_FLOAT; case NC_DOUBLE : return X_SIZEOF_DOUBLE; case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } /* default */ assert("ncx_szof invalid type" == 0); return 0; } /* * 'compile' the shape and len of a variable * Formerly NC_var_shape(var, dims) */ int NC_var_shape(NC_var *varp, const NC_dimarray *dims) { size_t *shp, *dsp, *op; int *ip; const NC_dim *dimp; size_t product = 1; varp->xsz = ncx_szof(varp->type); if(varp->ndims == 0) { goto out; } /* * use the user supplied dimension indices * to determine the shape */ for(ip = varp->dimids, op = varp->shape ; ip < &varp->dimids[varp->ndims]; ip++, op++) { if(*ip < 0 || (size_t) (*ip) >= ((dims != NULL) ? dims->nelems : 1) ) return NC_EBADDIM; dimp = elem_NC_dimarray(dims, (size_t)*ip); *op = dimp->size; if(*op == NC_UNLIMITED && ip != varp->dimids) return NC_EUNLIMPOS; } /* * Compute the dsizes */ /* ndims is > 0 here */ for(shp = varp->shape + varp->ndims -1, dsp = varp->dsizes + varp->ndims -1; shp >= varp->shape; shp--, dsp--) { if(!(shp == varp->shape && IS_RECVAR(varp))) product *= *shp; *dsp = product; } out : if( varp->xsz <= X_UINT_MAX / product ) /* if integer multiply will not overflow */ { varp->len = product * varp->xsz; } else { /* OK for last var to be "too big", indicated by this special len */ varp->len = X_UINT_MAX; } switch(varp->type) { case NC_BYTE : case NC_CHAR : case NC_SHORT : if( varp->len%4 != 0 ) { varp->len += 4 - varp->len%4; /* round up */ /* *dsp += 4 - *dsp%4; */ } break; default: /* already aligned */ break; } #if 0 arrayp("\tshape", varp->ndims, varp->shape); arrayp("\tdsizes", varp->ndims, varp->dsizes); #endif return NC_NOERR; } /* * Check whether variable size is less than or equal to vlen_max, * without overflowing in arithmetic calculations. If OK, return 1, * else, return 0. For CDF1 format or for CDF2 format on non-LFS * platforms, vlen_max should be 2^31 - 4, but for CDF2 format on * systems with LFS it should be 2^32 - 4. */ int NC_check_vlen(NC_var *varp, size_t vlen_max) { size_t prod=varp->xsz; /* product of xsz and dimensions so far */ int ii; for(ii = IS_RECVAR(varp) ? 1 : 0; ii < (int)varp->ndims; ii++) { if (varp->shape[ii] > vlen_max / prod) { return 0; /* size in bytes won't fit in a 32-bit int */ } prod *= varp->shape[ii]; } return 1; /* OK */ } /* * Given valid ncp and varid, return var * else NULL on error * Formerly NC_hlookupvar() */ NC_var * NC_lookupvar(NC *ncp, int varid) { NC_var *varp; if(varid == NC_GLOBAL) { /* Global is error in this context */ return(NULL); } varp = elem_NC_vararray(&ncp->vars, (size_t)varid); if(varp == NULL) { return NULL; } assert(varp != NULL); return(varp); } /* Public */ int nc_def_var( int ncid, const char *name, nc_type type, int ndims, const int *dimids, int *varidp) { int status; NC *ncp; int varid; NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(!NC_indef(ncp)) { return NC_ENOTINDEFINE; } status = NC_check_name(name); if(status != NC_NOERR) return status; status = nc_cktype(type); if(status != NC_NOERR) return status; /* cast needed for braindead systems with signed size_t */ if((unsigned long) ndims > X_INT_MAX) /* Backward compat */ { return NC_EINVAL; } if(ncp->vars.nelems >= NC_MAX_VARS) { return NC_EMAXVARS; } varid = NC_findvar(&ncp->vars, name, &varp); if(varid != -1) { return NC_ENAMEINUSE; } varp = new_NC_var(name, type, ndims, dimids); if(varp == NULL) return NC_ENOMEM; status = NC_var_shape(varp, &ncp->dims); if(status != NC_NOERR) { free_NC_var(varp); return status; } status = incr_NC_vararray(&ncp->vars, varp); if(status != NC_NOERR) { free_NC_var(varp); return status; } if(varidp != NULL) *varidp = (int)ncp->vars.nelems -1; /* varid */ return NC_NOERR; } int nc_inq_varid(int ncid, const char *name, int *varid_ptr) { int status; NC *ncp; NC_var *varp; int varid; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; varid = NC_findvar(&ncp->vars, name, &varp); if(varid == -1) { return NC_ENOTVAR; } *varid_ptr = varid; return NC_NOERR; } int nc_inq_var(int ncid, int varid, char *name, nc_type *typep, int *ndimsp, int *dimids, int *nattsp) { int status; NC *ncp; NC_var *varp; size_t ii; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; varp = elem_NC_vararray(&ncp->vars, (size_t)varid); if(varp == NULL) return NC_ENOTVAR; if(name != NULL) { (void) strncpy(name, varp->name->cp, varp->name->nchars); name[varp->name->nchars] = 0; } if(typep != 0) *typep = varp->type; if(ndimsp != 0) { *ndimsp = (int) varp->ndims; } if(dimids != 0) { for(ii = 0; ii < varp->ndims; ii++) { dimids[ii] = varp->dimids[ii]; } } if(nattsp != 0) { *nattsp = (int) varp->attrs.nelems; } return NC_NOERR; } int nc_inq_varname(int ncid, int varid, char *name) { int status; NC *ncp; NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; varp = elem_NC_vararray(&ncp->vars, (size_t)varid); if(varp == NULL) return NC_ENOTVAR; if(name != NULL) { (void) strncpy(name, varp->name->cp, varp->name->nchars); name[varp->name->nchars] = 0; } return NC_NOERR; } int nc_inq_vartype(int ncid, int varid, nc_type *typep) { int status; NC *ncp; NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; varp = elem_NC_vararray(&ncp->vars, (size_t)varid); if(varp == NULL) return NC_ENOTVAR; if(typep != 0) *typep = varp->type; return NC_NOERR; } int nc_inq_varndims(int ncid, int varid, int *ndimsp) { int status; NC *ncp; NC_var *varp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; varp = elem_NC_vararray(&ncp->vars, (size_t)varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: is this the right error code? */ if(ndimsp != 0) { *ndimsp = (int) varp->ndims; } return NC_NOERR; } int nc_inq_vardimid(int ncid, int varid, int *dimids) { int status; NC *ncp; NC_var *varp; size_t ii; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; varp = elem_NC_vararray(&ncp->vars, (size_t)varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: is this the right error code? */ if(dimids != 0) { for(ii = 0; ii < varp->ndims; ii++) { dimids[ii] = varp->dimids[ii]; } } return NC_NOERR; } int nc_inq_varnatts(int ncid, int varid, int *nattsp) { int status; NC *ncp; NC_var *varp; if(varid == NC_GLOBAL) return nc_inq_natts(ncid, nattsp); status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; varp = elem_NC_vararray(&ncp->vars, (size_t)varid); if(varp == NULL) return NC_ENOTVAR; /* TODO: is this the right error code? */ if(nattsp != 0) { *nattsp = (int) varp->attrs.nelems; } return NC_NOERR; } int nc_rename_var(int ncid, int varid, const char *newname) { int status; NC *ncp; NC_var *varp; NC_string *old, *newStr; int other; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) { return NC_EPERM; } status = NC_check_name(newname); if(status != NC_NOERR) return status; /* check for name in use */ other = NC_findvar(&ncp->vars, newname, &varp); if(other != -1) { return NC_ENAMEINUSE; } varp = NC_lookupvar(ncp, varid); if(varp == NULL) { /* invalid varid */ return NC_ENOTVAR; /* TODO: is this the right error code? */ } old = varp->name; if(NC_indef(ncp)) { newStr = new_NC_string(strlen(newname),newname); if(newStr == NULL) return(-1); varp->name = newStr; free_NC_string(old); return NC_NOERR; } /* else, not in define mode */ status = set_NC_string(varp->name, newname); if(status != NC_NOERR) return status; set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } xdmf-2.1.dfsg.1/Utilities/vtknetcdf/attr.m40000644000175000017500000005114111606020250021676 0ustar amckinstryamckinstrydnl This is m4 source. dnl Process using m4 to produce 'C' language file. dnl dnl If you see this line, you can ignore the next one. /* Do not edit this file. It is produced from the corresponding .m4 source */ dnl /* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: attr.m4,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #include "nc.h" #include #include #include #include "ncx.h" #include "fbits.h" #include "rnd.h" #if defined(_MSC_VER) && (_MSC_VER >= 1400) # pragma warning ( disable : 4130 ) /* logical operation on address of string constant */ #endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ /* * Free attr * Formerly NC_free_attr() */ void free_NC_attr(NC_attr *attrp) { if(attrp == NULL) return; free_NC_string(attrp->name); free(attrp); } /* * How much space will 'nelems' of 'type' take in * external representation (as the values of an attribute)? */ static size_t ncx_len_NC_attrV(nc_type type, size_t nelems) { switch(type) { case NC_BYTE: case NC_CHAR: return ncx_len_char(nelems); case NC_SHORT: return ncx_len_short(nelems); case NC_INT: return ncx_len_int(nelems); case NC_FLOAT: return ncx_len_float(nelems); case NC_DOUBLE: return ncx_len_double(nelems); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } /* default */ assert("ncx_len_NC_attr bad type" == 0); return 0; } NC_attr * new_x_NC_attr( NC_string *strp, nc_type type, size_t nelems) { NC_attr *attrp; const size_t xsz = ncx_len_NC_attrV(type, nelems); size_t sz = M_RNDUP(sizeof(NC_attr)); assert(!(xsz == 0 && nelems != 0)); sz += xsz; attrp = (NC_attr *) malloc(sz); if(attrp == NULL ) return NULL; attrp->xsz = xsz; attrp->name = strp; attrp->type = type; attrp->nelems = nelems; if(xsz != 0) attrp->xvalue = (char *)attrp + M_RNDUP(sizeof(NC_attr)); else attrp->xvalue = NULL; return(attrp); } /* * Formerly NC_new_attr(name,type,count,value) */ static NC_attr * new_NC_attr( const char *name, nc_type type, size_t nelems) { NC_string *strp; NC_attr *attrp; assert(name != NULL && *name != 0); strp = new_NC_string(strlen(name), name); if(strp == NULL) return NULL; attrp = new_x_NC_attr(strp, type, nelems); if(attrp == NULL) { free_NC_string(strp); return NULL; } return(attrp); } static NC_attr * dup_NC_attr(const NC_attr *rattrp) { NC_attr *attrp = new_NC_attr(rattrp->name->cp, rattrp->type, rattrp->nelems); if(attrp == NULL) return NULL; (void) memcpy(attrp->xvalue, rattrp->xvalue, rattrp->xsz); return attrp; } /* attrarray */ /* * Free the stuff "in" (referred to by) an NC_attrarray. * Leaves the array itself allocated. */ void free_NC_attrarrayV0(NC_attrarray *ncap) { assert(ncap != NULL); if(ncap->nelems == 0) return; assert(ncap->value != NULL); { NC_attr **app = ncap->value; NC_attr *const *const end = &app[ncap->nelems]; for( /*NADA*/; app < end; app++) { free_NC_attr(*app); *app = NULL; } } ncap->nelems = 0; } /* * Free NC_attrarray values. * formerly NC_free_array() */ void free_NC_attrarrayV(NC_attrarray *ncap) { assert(ncap != NULL); if(ncap->nalloc == 0) return; assert(ncap->value != NULL); free_NC_attrarrayV0(ncap); free(ncap->value); ncap->value = NULL; ncap->nalloc = 0; } int dup_NC_attrarrayV(NC_attrarray *ncap, const NC_attrarray *ref) { int status = NC_NOERR; assert(ref != NULL); assert(ncap != NULL); if(ref->nelems != 0) { const size_t sz = ref->nelems * sizeof(NC_attr *); ncap->value = (NC_attr **) malloc(sz); if(ncap->value == NULL) return NC_ENOMEM; (void) memset(ncap->value, 0, sz); ncap->nalloc = ref->nelems; } ncap->nelems = 0; { NC_attr **app = ncap->value; const NC_attr **drpp = (const NC_attr **)ref->value; NC_attr *const *const end = &app[ref->nelems]; for( /*NADA*/; app < end; drpp++, app++, ncap->nelems++) { *app = dup_NC_attr(*drpp); if(*app == NULL) { status = NC_ENOMEM; break; } } } if(status != NC_NOERR) { free_NC_attrarrayV(ncap); return status; } assert(ncap->nelems == ref->nelems); return NC_NOERR; } /* * Add a new handle on the end of an array of handles * Formerly NC_incr_array(array, tail) */ static int incr_NC_attrarray(NC_attrarray *ncap, NC_attr *newelemp) { NC_attr **vp; assert(ncap != NULL); if(ncap->nalloc == 0) { assert(ncap->nelems == 0); vp = (NC_attr **) malloc(NC_ARRAY_GROWBY * sizeof(NC_attr *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc = NC_ARRAY_GROWBY; } else if(ncap->nelems +1 > ncap->nalloc) { vp = (NC_attr **) realloc(ncap->value, (ncap->nalloc + NC_ARRAY_GROWBY) * sizeof(NC_attr *)); if(vp == NULL) return NC_ENOMEM; ncap->value = vp; ncap->nalloc += NC_ARRAY_GROWBY; } if(newelemp != NULL) { ncap->value[ncap->nelems] = newelemp; ncap->nelems++; } return NC_NOERR; } NC_attr * elem_NC_attrarray(const NC_attrarray *ncap, size_t elem) { assert(ncap != NULL); /* cast needed for braindead systems with signed size_t */ if(ncap->nelems == 0 || (unsigned long) elem >= ncap->nelems) return NULL; assert(ncap->value != NULL); return ncap->value[elem]; } /* End attarray per se */ /* * Given ncp and varid, return ptr to array of attributes * else NULL on error */ static NC_attrarray * NC_attrarray0( NC *ncp, int varid) { NC_attrarray *ap; if(varid == NC_GLOBAL) /* Global attribute, attach to cdf */ { ap = &ncp->attrs; } else if(varid >= 0 && (size_t) varid < ncp->vars.nelems) { NC_var **vpp; vpp = (NC_var **)ncp->vars.value; vpp += varid; ap = &(*vpp)->attrs; } else { ap = NULL; } return(ap); } /* * Step thru NC_ATTRIBUTE array, seeking match on name. * return match or NULL if Not Found. */ NC_attr ** NC_findattr(const NC_attrarray *ncap, const char *name) { NC_attr **attrpp; size_t attrid; size_t slen; assert(ncap != NULL); if(ncap->nelems == 0) return NULL; attrpp = (NC_attr **) ncap->value; slen = strlen(name); for(attrid = 0; attrid < ncap->nelems; attrid++, attrpp++) { if(strlen((*attrpp)->name->cp) == slen && strncmp((*attrpp)->name->cp, name, slen) == 0) { return(attrpp); /* Normal return */ } } return(NULL); } /* * Look up by ncid, varid and name, return NULL if not found */ static int NC_lookupattr(int ncid, int varid, const char *name, /* attribute name */ NC_attr **attrpp) /* modified on return */ { int status; NC *ncp; NC_attrarray *ncap; NC_attr **tmp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; tmp = NC_findattr(ncap, name); if(tmp == NULL) return NC_ENOTATT; if(attrpp != NULL) *attrpp = *tmp; return ENOERR; } /* Public */ int nc_inq_attname(int ncid, int varid, int attnum, char *name) { int status; NC *ncp; NC_attrarray *ncap; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; attrp = elem_NC_attrarray(ncap, (size_t)attnum); if(attrp == NULL) return NC_ENOTATT; (void) strncpy(name, attrp->name->cp, attrp->name->nchars); name[attrp->name->nchars] = 0; return NC_NOERR; } int nc_inq_attid(int ncid, int varid, const char *name, int *attnump) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; attrpp = NC_findattr(ncap, name); if(attrpp == NULL) return NC_ENOTATT; if(attnump != NULL) *attnump = (int)(attrpp - ncap->value); return NC_NOERR; } int nc_inq_atttype(int ncid, int varid, const char *name, nc_type *datatypep) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(datatypep != NULL) *datatypep = attrp->type; return NC_NOERR; } int nc_inq_attlen(int ncid, int varid, const char *name, size_t *lenp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(lenp != NULL) *lenp = attrp->nelems; return NC_NOERR; } int nc_inq_att(int ncid, int varid, const char *name, /* input, attribute name */ nc_type *datatypep, size_t *lenp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(datatypep != NULL) *datatypep = attrp->type; if(lenp != NULL) *lenp = attrp->nelems; return NC_NOERR; } int nc_rename_att( int ncid, int varid, const char *name, const char *newname) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **tmp; NC_attr *attrp; NC_string *newStr, *old; /* sortof inline clone of NC_lookupattr() */ status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = NC_check_name(newname); if(status != NC_NOERR) return status; tmp = NC_findattr(ncap, name); if(tmp == NULL) return NC_ENOTATT; attrp = *tmp; /* end inline clone NC_lookupattr() */ if(NC_findattr(ncap, newname) != NULL) { /* name in use */ return NC_ENAMEINUSE; } old = attrp->name; if(NC_indef(ncp)) { newStr = new_NC_string(strlen(newname), newname); if( newStr == NULL) return NC_ENOMEM; attrp->name = newStr; free_NC_string(old); return NC_NOERR; } /* else */ status = set_NC_string(old, newname); if( status != NC_NOERR) return status; set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } int nc_copy_att(int ncid_in, int varid_in, const char *name, int ncid_out, int ovarid) { int status; NC_attr *iattrp; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_lookupattr(ncid_in, varid_in, name, &iattrp); if(status != NC_NOERR) return status; status = NC_check_id(ncid_out, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, ovarid); if(ncap == NULL) return NC_ENOTVAR; attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { attrp = *attrpp; /* convenience */ if(iattrp->xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = iattrp->xsz; attrp->type = iattrp->type; attrp->nelems = iattrp->nelems; (void) memcpy(attrp->xvalue, iattrp->xvalue, iattrp->xsz); set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } attrp = new_NC_attr(name, iattrp->type, iattrp->nelems); if(attrp == NULL) return NC_ENOMEM; (void) memcpy(attrp->xvalue, iattrp->xvalue, iattrp->xsz); if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { status = incr_NC_attrarray(ncap, attrp); if(status != NC_NOERR) { free_NC_attr(attrp); return status; } } return NC_NOERR; } int nc_del_att(int ncid, int varid, const char *name) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; int attrid; size_t slen; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(!NC_indef(ncp)) return NC_ENOTINDEFINE; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; /* sortof inline NC_findattr() */ slen = strlen(name); attrpp = (NC_attr **) ncap->value; for(attrid = 0; (size_t) attrid < ncap->nelems; attrid++, attrpp++) { if( slen == (*attrpp)->name->nchars && strncmp(name, (*attrpp)->name->cp, slen) == 0) { old = *attrpp; break; } } if( (size_t) attrid == ncap->nelems ) return NC_ENOTATT; /* end inline NC_findattr() */ /* shuffle down */ for(attrid++; (size_t) attrid < ncap->nelems; attrid++) { *attrpp = *(attrpp + 1); attrpp++; } *attrpp = NULL; /* decrement count */ ncap->nelems--; free_NC_attr(old); return NC_NOERR; } dnl dnl XNCX_PAD_PUTN(Type) dnl define(`XNCX_PAD_PUTN',dnl `dnl static int ncx_pad_putn_I$1(void **xpp, size_t nelems, const $1 *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_putn_schar_$1(xpp, nelems, tp); case NC_SHORT: return ncx_pad_putn_short_$1(xpp, nelems, tp); case NC_INT: return ncx_putn_int_$1(xpp, nelems, tp); case NC_FLOAT: return ncx_putn_float_$1(xpp, nelems, tp); case NC_DOUBLE: return ncx_putn_double_$1(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_putn_I$1 invalid type" == 0); return NC_EBADTYPE; } ')dnl dnl dnl XNCX_PAD_GETN(Type) dnl define(`XNCX_PAD_GETN',dnl `dnl static int ncx_pad_getn_I$1(const void **xpp, size_t nelems, $1 *tp, nc_type type) { switch(type) { case NC_CHAR: return NC_ECHAR; case NC_BYTE: return ncx_pad_getn_schar_$1(xpp, nelems, tp); case NC_SHORT: return ncx_pad_getn_short_$1(xpp, nelems, tp); case NC_INT: return ncx_getn_int_$1(xpp, nelems, tp); case NC_FLOAT: return ncx_getn_float_$1(xpp, nelems, tp); case NC_DOUBLE: return ncx_getn_double_$1(xpp, nelems, tp); case NC_NAT: break; /* Some compilers complain if enums are missing from a switch */ } assert("ncx_pad_getn_I$1 invalid type" == 0); return NC_EBADTYPE; } ')dnl dnl Implement XNCX_PAD_PUTN(uchar) XNCX_PAD_GETN(uchar) XNCX_PAD_PUTN(schar) XNCX_PAD_GETN(schar) XNCX_PAD_PUTN(short) XNCX_PAD_GETN(short) XNCX_PAD_PUTN(int) XNCX_PAD_GETN(int) XNCX_PAD_PUTN(long) XNCX_PAD_GETN(long) XNCX_PAD_PUTN(float) XNCX_PAD_GETN(float) XNCX_PAD_PUTN(double) XNCX_PAD_GETN(double) int nc_put_att_text(int ncid, int varid, const char *name, size_t nelems, const char *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = NC_check_name(name); if(status != NC_NOERR) return status; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(NC_CHAR, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = NC_CHAR; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_text(&xp, nelems, value); if(status != NC_NOERR) return status; } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { status = NC_sync(ncp); if(status != NC_NOERR) return status; } return NC_NOERR; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } attrp = new_NC_attr(name, NC_CHAR, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_text(&xp, nelems, value); if(status != NC_NOERR) return status; } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { status = incr_NC_attrarray(ncap, attrp); if(status != NC_NOERR) { free_NC_attr(attrp); return status; } } return NC_NOERR; } int nc_get_att_text(int ncid, int varid, const char *name, char *str) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type != NC_CHAR) return NC_ECHAR; /* else */ { const void *xp = attrp->xvalue; return ncx_pad_getn_text(&xp, attrp->nelems, str); } } dnl dnl NC_PUT_ATT(Abbrv, Type) dnl define(`NC_PUT_ATT',dnl `dnl int nc_put_att_$1(int ncid, int varid, const char *name, nc_type type, size_t nelems, const $2 *value) { int status; NC *ncp; NC_attrarray *ncap; NC_attr **attrpp; NC_attr *old = NULL; NC_attr *attrp; status = NC_check_id(ncid, &ncp); if(status != NC_NOERR) return status; if(NC_readonly(ncp)) return NC_EPERM; ncap = NC_attrarray0(ncp, varid); if(ncap == NULL) return NC_ENOTVAR; status = nc_cktype(type); if(status != NC_NOERR) return status; if(type == NC_CHAR) return NC_ECHAR; /* cast needed for braindead systems with signed size_t */ if((unsigned long) nelems > X_INT_MAX) /* backward compat */ return NC_EINVAL; /* Invalid nelems */ if(nelems != 0 && value == NULL) return NC_EINVAL; /* Null arg */ attrpp = NC_findattr(ncap, name); if(attrpp != NULL) /* name in use */ { if(!NC_indef(ncp) ) { const size_t xsz = ncx_len_NC_attrV(type, nelems); attrp = *attrpp; /* convenience */ if(xsz > attrp->xsz) return NC_ENOTINDEFINE; /* else, we can reuse existing without redef */ attrp->xsz = xsz; attrp->type = type; attrp->nelems = nelems; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_I$1(&xp, nelems, value, type); } set_NC_hdirty(ncp); if(NC_doHsync(ncp)) { const int lstatus = NC_sync(ncp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_I$1 */ if(lstatus != ENOERR) return lstatus; } return status; } /* else, redefine using existing array slot */ old = *attrpp; } else { if(!NC_indef(ncp)) return NC_ENOTINDEFINE; if(ncap->nelems >= NC_MAX_ATTRS) return NC_EMAXATTS; } status = NC_check_name(name); if(status != NC_NOERR) return status; attrp = new_NC_attr(name, type, nelems); if(attrp == NULL) return NC_ENOMEM; if(nelems != 0) { void *xp = attrp->xvalue; status = ncx_pad_putn_I$1(&xp, nelems, value, type); } if(attrpp != NULL) { assert(old != NULL); *attrpp = attrp; free_NC_attr(old); } else { const int lstatus = incr_NC_attrarray(ncap, attrp); /* * N.B.: potentially overrides NC_ERANGE * set by ncx_pad_putn_I$1 */ if(lstatus != NC_NOERR) { free_NC_attr(attrp); return lstatus; } } return status; } ')dnl dnl dnl NC_GET_ATT(Abbrv, Type) dnl define(`NC_GET_ATT',dnl `dnl int nc_get_att_$1(int ncid, int varid, const char *name, $2 *tp) { int status; NC_attr *attrp; status = NC_lookupattr(ncid, varid, name, &attrp); if(status != NC_NOERR) return status; if(attrp->nelems == 0) return NC_NOERR; if(attrp->type == NC_CHAR) return NC_ECHAR; { const void *xp = attrp->xvalue; return ncx_pad_getn_I$1(&xp, attrp->nelems, tp, attrp->type); } } ')dnl NC_PUT_ATT(schar, signed char) NC_GET_ATT(schar, signed char) NC_PUT_ATT(uchar, unsigned char) NC_GET_ATT(uchar, unsigned char) NC_PUT_ATT(short, short) NC_GET_ATT(short, short) NC_PUT_ATT(int, int) NC_GET_ATT(int, int) NC_PUT_ATT(long, long) NC_GET_ATT(long, long) NC_PUT_ATT(float, float) NC_GET_ATT(float, float) NC_PUT_ATT(double, double) NC_GET_ATT(double, double) xdmf-2.1.dfsg.1/Utilities/vtknetcdf/nc3convert.h0000644000175000017500000001657611606020250022734 0ustar amckinstryamckinstry#ifndef _NETCDF3_CONV #define _NETCDF3_CONV_ #include /* size_t, ptrdiff_t */ #include /* netcdf functions sometimes return system errors */ #if defined(__cplusplus) extern "C" { #endif /* * The Interface */ #define nc_inq_format nc3_inq_format #define nc_inq_libvers nc3_inq_libvers #define nc_strerror nc3_strerror #define nc__create nc3__create #define nc_create nc3_create #define nc__open nc3__open #define nc_open nc3_open #define nc_set_fill nc3_set_fill #define nc_redef nc3_redef #define nc__enddef nc3__enddef #define nc_enddef nc3_enddef #define nc_sync nc3_sync #define nc_abort nc3_abort #define nc_close nc3_close #define nc_inq nc3_inq #define nc_inq_ndims nc3_inq_ndims #define nc_inq_nvars nc3_inq_nvars #define nc_inq_natts nc3_inq_natts #define nc_inq_unlimdim nc3_inq_unlimdim #define nc_inq_format nc3_inq_format /* Begin _dim */ #define nc_def_dim nc3_def_dim #define nc_inq_dimid nc3_inq_dimid #define nc_inq_dim nc3_inq_dim #define nc_inq_dimname nc3_inq_dimname #define nc_inq_dimlen nc3_inq_dimlen #define nc_rename_dim nc3_rename_dim /* End _dim */ /* Begin _att */ #define nc_inq_att nc3_inq_att #define nc_inq_attid nc3_inq_attid #define nc_inq_atttype nc3_inq_atttype #define nc_inq_attlen nc3_inq_attlen #define nc_inq_attname nc3_inq_attname #define nc_copy_att nc3_copy_att #define nc_rename_att nc3_rename_att #define nc_del_att nc3_del_att /* End _att */ /* Begin {put,get}_att */ #define nc_put_att nc3_put_att #define nc_get_att nc3_get_att #define nc_put_att_text nc3_put_att_text #define nc_get_att_text nc3_get_att_text #define nc_put_att_uchar nc3_put_att_uchar #define nc_get_att_uchar nc3_get_att_uchar #define nc_put_att_schar nc3_put_att_schar #define nc_get_att_schar nc3_get_att_schar #define nc_put_att_short nc3_put_att_short #define nc_get_att_short nc3_get_att_short #define nc_put_att_int nc3_put_att_int #define nc_get_att_int nc3_get_att_int #define nc_put_att_long nc3_put_att_long #define nc_get_att_long nc3_get_att_long #define nc_put_att_float nc3_put_att_float #define nc_get_att_float nc3_get_att_float #define nc_put_att_double nc3_put_att_double #define nc_get_att_double nc3_get_att_double /* End {put,get}_att */ /* Begin _var */ #define nc_def_var nc3_def_var #define nc_inq_var nc3_inq_var #define nc_inq_varid nc3_inq_varid #define nc_inq_varname nc3_inq_varname #define nc_inq_vartype nc3_inq_vartype #define nc_inq_varndims nc3_inq_varndims #define nc_inq_vardimid nc3_inq_vardimid #define nc_inq_varnatts nc3_inq_varnatts #define nc_rename_var nc3_rename_var #define nc_copy_var nc3_copy_var /* support the old name for now */ #define ncvarcpy(ncid_in, varid, ncid_out) ncvarcopy((ncid_in), (varid), (ncid_out)) /* End _var */ /* Begin {put,get}_var1 */ #define nc_put_var1 nc3_put_var1 #define nc_get_var1 nc3_get_var1 #define nc_put_var1_text nc3_put_var1_text #define nc_get_var1_text nc3_get_var1_text #define nc_put_var1_uchar nc3_put_var1_uchar #define nc_get_var1_uchar nc3_get_var1_uchar #define nc_put_var1_schar nc3_put_var1_schar #define nc_get_var1_schar nc3_get_var1_schar #define nc_put_var1_short nc3_put_var1_short #define nc_get_var1_short nc3_get_var1_short #define nc_put_var1_int nc3_put_var1_int #define nc_get_var1_int nc3_get_var1_int #define nc_put_var1_long nc3_put_var1_long #define nc_get_var1_long nc3_get_var1_long #define nc_put_var1_float nc3_put_var1_float #define nc_get_var1_float nc3_get_var1_float #define nc_put_var1_double nc3_put_var1_double #define nc_get_var1_double nc3_get_var1_double /* End {put,get}_var1 */ /* Begin {put,get}_vara */ #define nc_put_vara nc3_put_vara #define nc_get_vara nc3_get_vara #define nc_put_vara_text nc3_put_vara_text #define nc_put_vara_text nc3_put_vara_text #define nc_get_vara_text nc3_get_vara_text #define nc_put_vara_uchar nc3_put_vara_uchar #define nc_get_vara_uchar nc3_get_vara_uchar #define nc_put_vara_schar nc3_put_vara_schar #define nc_get_vara_schar nc3_get_vara_schar #define nc_put_vara_short nc3_put_vara_short #define nc_get_vara_short nc3_get_vara_short #define nc_put_vara_int nc3_put_vara_int #define nc_get_vara_int nc3_get_vara_int #define nc_put_vara_long nc3_put_vara_long #define nc_get_vara_long nc3_get_vara_long #define nc_put_vara_float nc3_put_vara_float #define nc_get_vara_float nc3_get_vara_float #define nc_put_vara_double nc3_put_vara_double #define nc_get_vara_double nc3_get_vara_double /* End {put,get}_vara */ /* Begin {put,get}_vars */ #define nc_put_vars nc3_put_vars #define nc_get_vars nc3_get_vars #define nc_put_vars_text nc3_put_vars_text #define nc_get_vars_text nc3_get_vars_text #define nc_put_vars_uchar nc3_put_vars_uchar #define nc_get_vars_uchar nc3_get_vars_uchar #define nc_put_vars_schar nc3_put_vars_schar #define nc_get_vars_schar nc3_get_vars_schar #define nc_put_vars_short nc3_put_vars_short #define nc_get_vars_short nc3_get_vars_short #define nc_put_vars_int nc3_put_vars_int #define nc_get_vars_int nc3_get_vars_int #define nc_put_vars_long nc3_put_vars_long #define nc_get_vars_long nc3_get_vars_long #define nc_put_vars_float nc3_put_vars_float #define nc_get_vars_float nc3_get_vars_float #define nc_put_vars_double nc3_put_vars_double #define nc_get_vars_double nc3_get_vars_double /* End {put,get}_vars */ /* Begin {put,get}_varm */ #define nc_put_varm nc3_put_varm #define nc_get_varm nc3_get_varm #define nc_put_varm_text nc3_put_varm_text #define nc_get_varm_text nc3_get_varm_text #define nc_put_varm_uchar nc3_put_varm_uchar #define nc_get_varm_uchar nc3_get_varm_uchar #define nc_put_varm_schar nc3_put_varm_schar #define nc_get_varm_schar nc3_get_varm_schar #define nc_put_varm_short nc3_put_varm_short #define nc_get_varm_short nc3_get_varm_short #define nc_put_varm_int nc3_put_varm_int #define nc_get_varm_int nc3_get_varm_int #define nc_put_varm_long nc3_put_varm_long #define nc_get_varm_long nc3_get_varm_long #define nc_put_varm_float nc3_put_varm_float #define nc_get_varm_float nc3_get_varm_float #define nc_put_varm_double nc3_put_varm_double #define nc_get_varm_double nc3_get_varm_double /* End {put,get}_varm */ /* Begin {put,get}_var */ #define nc_put_var_text nc3_put_var_text #define nc_get_var_text nc3_get_var_text #define nc_put_var_uchar nc3_put_var_uchar #define nc_get_var_uchar nc3_get_var_uchar #define nc_put_var_schar nc3_put_var_schar #define nc_get_var_schar nc3_get_var_schar #define nc_put_var_short nc3_put_var_short #define nc_get_var_short nc3_get_var_short #define nc_put_var_int nc3_put_var_int #define nc_get_var_int nc3_get_var_int #define nc_put_var_long nc3_put_var_long #define nc_get_var_long nc3_get_var_long #define nc_put_var_float nc3_put_var_float #define nc_get_var_float nc3_get_var_float #define nc_put_var_double nc3_put_var_double #define nc_get_var_double nc3_get_var_double /* End {put,get}_var */ #define nc_put_att nc3_put_att #define nc_get_att nc3_get_att /* #ifdef _CRAYMPP */ /* * Public interfaces to better support * CRAY multi-processor systems like T3E. * A tip of the hat to NERSC. */ /* * It turns out we need to declare and define * these public interfaces on all platforms * or things get ugly working out the * FORTRAN interface. On !_CRAYMPP platforms, * these functions work as advertised, but you * can only use "processor element" 0. */ #define nc__create_mp nc3__create_mp #define nc__open_mp nc3__open_mp #define nc_delete_mp nc3_delete_mp #define nc_set_base_pe nc3_set_base_pe #define nc_inq_base_pe nc3_inq_base_pe /* #endif _CRAYMPP */ #if defined(__cplusplus) } #endif #endif /* _NETCDF_ */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/onstack.h0000644000175000017500000000337611606020250022304 0ustar amckinstryamckinstry/* * Copyright 1997, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: onstack.h,v 1.1 2010-01-06 16:34:07 kwleiter Exp $ */ #ifndef _ONSTACK_H_ #define _ONSTACK_H_ /* include after ncconfig.h */ /** * This file provides definitions which allow us to * "allocate" arrays on the stack where possible. * (Where not possible, malloc and free are used.) * * The macro ALLOC_ONSTACK(name, type, nelems) is used to declare * an array of 'type' named 'name' which is 'nelems' long. * FREE_ONSTACK(name) is placed at the end of the scope of 'name' * to call 'free' if necessary. * * The macro ALLOC_ONSTACK wraps a call to alloca() on most systems. */ #if HAVE_ALLOCA /* * Implementation based on alloca() */ #if defined(__GNUC__) # if !defined(alloca) # define alloca __builtin_alloca # endif #else # if HAVE_ALLOCA_H # include # elif defined(_AIX) # pragma alloca # endif /* HAVE_ALLOCA_H */ #endif /* __GNUC__ */ # if !defined(ALLOCA_ARG_T) # define ALLOCA_ARG_T int /* the usual type of the alloca argument */ # endif # define ALLOC_ONSTACK(name, type, nelems) \ type *const name = (type *) alloca((ALLOCA_ARG_T)((nelems) * sizeof(type))) # define FREE_ONSTACK(name) #elif defined(_CRAYC) && !defined(__crayx1) && !__cplusplus && __STDC__ > 1 /* * Cray C allows sizing of arrays with non-constant values. */ # define ALLOC_ONSTACK(name, type, nelems) \ type name[nelems] # define FREE_ONSTACK(name) #else /* * Default implementation. When all else fails, use malloc/free. */ # define ALLOC_ONSTACK(name, type, nelems) \ type *const name = (type *) malloc((nelems) * sizeof(type)) # define FREE_ONSTACK(name) \ free(name) #endif #endif /* _ONSTACK_H_ */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/vtk_netcdf_mangle.h0000644000175000017500000005342211606020250024311 0ustar amckinstryamckinstry#ifndef vtk_netcdf_mangle_h #define vtk_netcdf_mangle_h /* This header file mangles all symbols exported from the netcdf library. It is included in all files while building the netcdf library. Due to namespace pollution, no netcdf headers should be included in .h files in VTK. The following command was used to obtain the symbol list: nm libvtkNetCDF.a |grep " [TRD] " This is the way to recreate the whole list: nm bin/libvtkNetCDF.so |grep " [TRD] " | awk '{ print "#define "$3" vtk_netcdf_"$3 }' | \ grep -v vtk_netcdf__fini | grep -v vtk_netcdf__init | sort Note that _fini and _init should be excluded because they are not functions implemented by the library but are rather created by the linker and used when the shared library is loaded/unloaded from an executable. */ #define default_create_format vtk_netcdf_default_create_format #define dup_NC_attrarrayV vtk_netcdf_dup_NC_attrarrayV #define dup_NC_dimarrayV vtk_netcdf_dup_NC_dimarrayV #define dup_NC_vararrayV vtk_netcdf_dup_NC_vararrayV #define elem_NC_attrarray vtk_netcdf_elem_NC_attrarray #define elem_NC_dimarray vtk_netcdf_elem_NC_dimarray #define fill_NC_var vtk_netcdf_fill_NC_var #define find_NC_Udim vtk_netcdf_find_NC_Udim #define free_NC_attrarrayV0 vtk_netcdf_free_NC_attrarrayV0 #define free_NC_attrarrayV vtk_netcdf_free_NC_attrarrayV #define free_NC_attr vtk_netcdf_free_NC_attr #define free_NC_dimarrayV0 vtk_netcdf_free_NC_dimarrayV0 #define free_NC_dimarrayV vtk_netcdf_free_NC_dimarrayV #define free_NC_dim vtk_netcdf_free_NC_dim #define free_NC_string vtk_netcdf_free_NC_string #define free_NC_vararrayV0 vtk_netcdf_free_NC_vararrayV0 #define free_NC_vararrayV vtk_netcdf_free_NC_vararrayV #define free_NC_var vtk_netcdf_free_NC_var #define nc_abort vtk_netcdf_nc_abort #define ncabort vtk_netcdf_ncabort #define nc_advise vtk_netcdf_nc_advise #define ncattcopy vtk_netcdf_ncattcopy #define ncattdel vtk_netcdf_ncattdel #define ncattget vtk_netcdf_ncattget #define ncattinq vtk_netcdf_ncattinq #define ncattname vtk_netcdf_ncattname #define ncattput vtk_netcdf_ncattput #define ncattrename vtk_netcdf_ncattrename #define NC_calcsize vtk_netcdf_NC_calcsize #define NC_check_id vtk_netcdf_NC_check_id #define NC_check_name vtk_netcdf_NC_check_name #define NC_check_vlen vtk_netcdf_NC_check_vlen #define nc_cktype vtk_netcdf_nc_cktype #define nc_close vtk_netcdf_nc_close #define ncclose vtk_netcdf_ncclose #define nc_copy_att vtk_netcdf_nc_copy_att #define nc_copy_var vtk_netcdf_nc_copy_var #define nc__create_mp vtk_netcdf_nc__create_mp #define nc__create vtk_netcdf_nc__create #define nc_create vtk_netcdf_nc_create #define nccreate vtk_netcdf_nccreate #define nc_def_dim vtk_netcdf_nc_def_dim #define nc_def_var vtk_netcdf_nc_def_var #define nc_del_att vtk_netcdf_nc_del_att #define nc_delete_mp vtk_netcdf_nc_delete_mp #define nc_delete vtk_netcdf_nc_delete #define ncdimdef vtk_netcdf_ncdimdef #define ncdimid vtk_netcdf_ncdimid #define ncdiminq vtk_netcdf_ncdiminq #define ncdimrename vtk_netcdf_ncdimrename #define nc__enddef vtk_netcdf_nc__enddef #define nc_enddef vtk_netcdf_nc_enddef #define ncendef vtk_netcdf_ncendef #define ncerr vtk_netcdf_ncerr #define NC_findattr vtk_netcdf_NC_findattr #define NC_findvar vtk_netcdf_NC_findvar #define nc_get_att_double vtk_netcdf_nc_get_att_double #define nc_get_att_float vtk_netcdf_nc_get_att_float #define nc_get_att_int vtk_netcdf_nc_get_att_int #define nc_get_att_long vtk_netcdf_nc_get_att_long #define nc_get_att_schar vtk_netcdf_nc_get_att_schar #define nc_get_att_short vtk_netcdf_nc_get_att_short #define nc_get_att_text vtk_netcdf_nc_get_att_text #define nc_get_att_uchar vtk_netcdf_nc_get_att_uchar #define nc_get_att vtk_netcdf_nc_get_att #define nc_get_NC vtk_netcdf_nc_get_NC #define nc_get_rec vtk_netcdf_nc_get_rec #define nc_get_var1_double vtk_netcdf_nc_get_var1_double #define nc_get_var1_float vtk_netcdf_nc_get_var1_float #define nc_get_var1_int vtk_netcdf_nc_get_var1_int #define nc_get_var1_long vtk_netcdf_nc_get_var1_long #define nc_get_var1_schar vtk_netcdf_nc_get_var1_schar #define nc_get_var1_short vtk_netcdf_nc_get_var1_short #define nc_get_var1_text vtk_netcdf_nc_get_var1_text #define nc_get_var1_uchar vtk_netcdf_nc_get_var1_uchar #define nc_get_var1 vtk_netcdf_nc_get_var1 #define nc_get_vara_double vtk_netcdf_nc_get_vara_double #define nc_get_vara_float vtk_netcdf_nc_get_vara_float #define nc_get_vara_int vtk_netcdf_nc_get_vara_int #define nc_get_vara_long vtk_netcdf_nc_get_vara_long #define nc_get_vara_schar vtk_netcdf_nc_get_vara_schar #define nc_get_vara_short vtk_netcdf_nc_get_vara_short #define nc_get_vara_text vtk_netcdf_nc_get_vara_text #define nc_get_vara_uchar vtk_netcdf_nc_get_vara_uchar #define nc_get_vara vtk_netcdf_nc_get_vara #define nc_get_var_double vtk_netcdf_nc_get_var_double #define nc_get_var_float vtk_netcdf_nc_get_var_float #define nc_get_var_int vtk_netcdf_nc_get_var_int #define nc_get_var_long vtk_netcdf_nc_get_var_long #define nc_get_varm_double vtk_netcdf_nc_get_varm_double #define nc_get_varm_float vtk_netcdf_nc_get_varm_float #define nc_get_varm_int vtk_netcdf_nc_get_varm_int #define nc_get_varm_long vtk_netcdf_nc_get_varm_long #define nc_get_varm_schar vtk_netcdf_nc_get_varm_schar #define nc_get_varm_short vtk_netcdf_nc_get_varm_short #define nc_get_varm_text vtk_netcdf_nc_get_varm_text #define nc_get_varm_uchar vtk_netcdf_nc_get_varm_uchar #define nc_get_varm vtk_netcdf_nc_get_varm #define nc_get_var_schar vtk_netcdf_nc_get_var_schar #define nc_get_vars_double vtk_netcdf_nc_get_vars_double #define nc_get_vars_float vtk_netcdf_nc_get_vars_float #define nc_get_var_short vtk_netcdf_nc_get_var_short #define nc_get_vars_int vtk_netcdf_nc_get_vars_int #define nc_get_vars_long vtk_netcdf_nc_get_vars_long #define nc_get_vars_schar vtk_netcdf_nc_get_vars_schar #define nc_get_vars_short vtk_netcdf_nc_get_vars_short #define nc_get_vars_text vtk_netcdf_nc_get_vars_text #define nc_get_vars_uchar vtk_netcdf_nc_get_vars_uchar #define nc_get_vars vtk_netcdf_nc_get_vars #define nc_get_var_text vtk_netcdf_nc_get_var_text #define nc_get_var_uchar vtk_netcdf_nc_get_var_uchar #define nc_inq_attid vtk_netcdf_nc_inq_attid #define nc_inq_attlen vtk_netcdf_nc_inq_attlen #define nc_inq_attname vtk_netcdf_nc_inq_attname #define nc_inq_atttype vtk_netcdf_nc_inq_atttype #define nc_inq_att vtk_netcdf_nc_inq_att #define nc_inq_base_pe vtk_netcdf_nc_inq_base_pe #define nc_inq_dimid vtk_netcdf_nc_inq_dimid #define nc_inq_dimlen vtk_netcdf_nc_inq_dimlen #define nc_inq_dimname vtk_netcdf_nc_inq_dimname #define nc_inq_dim vtk_netcdf_nc_inq_dim #define nc_inq_format vtk_netcdf_nc_inq_format #define nc_inq_libvers vtk_netcdf_nc_inq_libvers #define nc_inq_natts vtk_netcdf_nc_inq_natts #define nc_inq_ndims vtk_netcdf_nc_inq_ndims #define nc_inq_nvars vtk_netcdf_nc_inq_nvars #define nc_inq_rec vtk_netcdf_nc_inq_rec #define ncinquire vtk_netcdf_ncinquire #define nc_inq_unlimdim vtk_netcdf_nc_inq_unlimdim #define nc_inq_vardimid vtk_netcdf_nc_inq_vardimid #define nc_inq_varid vtk_netcdf_nc_inq_varid #define nc_inq_varname vtk_netcdf_nc_inq_varname #define nc_inq_varnatts vtk_netcdf_nc_inq_varnatts #define nc_inq_varndims vtk_netcdf_nc_inq_varndims #define nc_inq_vartype vtk_netcdf_nc_inq_vartype #define nc_inq_var vtk_netcdf_nc_inq_var #define nc_inq vtk_netcdf_nc_inq #define ncio_close vtk_netcdf_ncio_close #define ncio_create vtk_netcdf_ncio_create #define ncio_filesize vtk_netcdf_ncio_filesize #define ncio_open vtk_netcdf_ncio_open #define ncio_pad_length vtk_netcdf_ncio_pad_length #define NC_lookupvar vtk_netcdf_NC_lookupvar #define nc__open_mp vtk_netcdf_nc__open_mp #define nc__open vtk_netcdf_nc__open #define nc_open vtk_netcdf_nc_open #define ncopen vtk_netcdf_ncopen #define ncopts vtk_netcdf_ncopts #define nc_put_att_double vtk_netcdf_nc_put_att_double #define nc_put_att_float vtk_netcdf_nc_put_att_float #define nc_put_att_int vtk_netcdf_nc_put_att_int #define nc_put_att_long vtk_netcdf_nc_put_att_long #define nc_put_att_schar vtk_netcdf_nc_put_att_schar #define nc_put_att_short vtk_netcdf_nc_put_att_short #define nc_put_att_text vtk_netcdf_nc_put_att_text #define nc_put_att_uchar vtk_netcdf_nc_put_att_uchar #define nc_put_att vtk_netcdf_nc_put_att #define nc_put_rec vtk_netcdf_nc_put_rec #define nc_put_var1_double vtk_netcdf_nc_put_var1_double #define nc_put_var1_float vtk_netcdf_nc_put_var1_float #define nc_put_var1_int vtk_netcdf_nc_put_var1_int #define nc_put_var1_long vtk_netcdf_nc_put_var1_long #define nc_put_var1_schar vtk_netcdf_nc_put_var1_schar #define nc_put_var1_short vtk_netcdf_nc_put_var1_short #define nc_put_var1_text vtk_netcdf_nc_put_var1_text #define nc_put_var1_uchar vtk_netcdf_nc_put_var1_uchar #define nc_put_var1 vtk_netcdf_nc_put_var1 #define nc_put_vara_double vtk_netcdf_nc_put_vara_double #define nc_put_vara_float vtk_netcdf_nc_put_vara_float #define nc_put_vara_int vtk_netcdf_nc_put_vara_int #define nc_put_vara_long vtk_netcdf_nc_put_vara_long #define nc_put_vara_schar vtk_netcdf_nc_put_vara_schar #define nc_put_vara_short vtk_netcdf_nc_put_vara_short #define nc_put_vara_text vtk_netcdf_nc_put_vara_text #define nc_put_vara_uchar vtk_netcdf_nc_put_vara_uchar #define nc_put_vara vtk_netcdf_nc_put_vara #define nc_put_var_double vtk_netcdf_nc_put_var_double #define nc_put_var_float vtk_netcdf_nc_put_var_float #define nc_put_var_int vtk_netcdf_nc_put_var_int #define nc_put_var_long vtk_netcdf_nc_put_var_long #define nc_put_varm_double vtk_netcdf_nc_put_varm_double #define nc_put_varm_float vtk_netcdf_nc_put_varm_float #define nc_put_varm_int vtk_netcdf_nc_put_varm_int #define nc_put_varm_long vtk_netcdf_nc_put_varm_long #define nc_put_varm_schar vtk_netcdf_nc_put_varm_schar #define nc_put_varm_short vtk_netcdf_nc_put_varm_short #define nc_put_varm_text vtk_netcdf_nc_put_varm_text #define nc_put_varm_uchar vtk_netcdf_nc_put_varm_uchar #define nc_put_varm vtk_netcdf_nc_put_varm #define nc_put_var_schar vtk_netcdf_nc_put_var_schar #define nc_put_vars_double vtk_netcdf_nc_put_vars_double #define nc_put_vars_float vtk_netcdf_nc_put_vars_float #define nc_put_var_short vtk_netcdf_nc_put_var_short #define nc_put_vars_int vtk_netcdf_nc_put_vars_int #define nc_put_vars_long vtk_netcdf_nc_put_vars_long #define nc_put_vars_schar vtk_netcdf_nc_put_vars_schar #define nc_put_vars_short vtk_netcdf_nc_put_vars_short #define nc_put_vars_text vtk_netcdf_nc_put_vars_text #define nc_put_vars_uchar vtk_netcdf_nc_put_vars_uchar #define nc_put_vars vtk_netcdf_nc_put_vars #define nc_put_var_text vtk_netcdf_nc_put_var_text #define nc_put_var_uchar vtk_netcdf_nc_put_var_uchar #define ncrecget vtk_netcdf_ncrecget #define ncrecinq vtk_netcdf_ncrecinq #define ncrecput vtk_netcdf_ncrecput #define nc_redef vtk_netcdf_nc_redef #define ncredef vtk_netcdf_ncredef #define nc_rename_att vtk_netcdf_nc_rename_att #define nc_rename_dim vtk_netcdf_nc_rename_dim #define nc_rename_var vtk_netcdf_nc_rename_var #define nc_set_base_pe vtk_netcdf_nc_set_base_pe #define nc_set_default_format vtk_netcdf_nc_set_default_format #define nc_set_fill vtk_netcdf_nc_set_fill #define ncsetfill vtk_netcdf_ncsetfill #define nc_strerror vtk_netcdf_nc_strerror #define nc_sync vtk_netcdf_nc_sync #define ncsync vtk_netcdf_ncsync #define NC_sync vtk_netcdf_NC_sync #define nctypelen vtk_netcdf_nctypelen #define ncvardef vtk_netcdf_ncvardef #define ncvarget1 vtk_netcdf_ncvarget1 #define ncvargetg vtk_netcdf_ncvargetg #define ncvargets vtk_netcdf_ncvargets #define ncvarget vtk_netcdf_ncvarget #define ncvarid vtk_netcdf_ncvarid #define ncvarinq vtk_netcdf_ncvarinq #define ncvarput1 vtk_netcdf_ncvarput1 #define ncvarputg vtk_netcdf_ncvarputg #define ncvarputs vtk_netcdf_ncvarputs #define ncvarput vtk_netcdf_ncvarput #define ncvarrename vtk_netcdf_ncvarrename #define NC_var_shape vtk_netcdf_NC_var_shape #define ncx_get_double_double vtk_netcdf_ncx_get_double_double #define ncx_get_double_float vtk_netcdf_ncx_get_double_float #define ncx_get_double_int vtk_netcdf_ncx_get_double_int #define ncx_get_double_long vtk_netcdf_ncx_get_double_long #define ncx_get_double_schar vtk_netcdf_ncx_get_double_schar #define ncx_get_double_short vtk_netcdf_ncx_get_double_short #define ncx_get_double_uchar vtk_netcdf_ncx_get_double_uchar #define ncx_get_float_double vtk_netcdf_ncx_get_float_double #define ncx_get_float_float vtk_netcdf_ncx_get_float_float #define ncx_get_float_int vtk_netcdf_ncx_get_float_int #define ncx_get_float_long vtk_netcdf_ncx_get_float_long #define ncx_get_float_schar vtk_netcdf_ncx_get_float_schar #define ncx_get_float_short vtk_netcdf_ncx_get_float_short #define ncx_get_float_uchar vtk_netcdf_ncx_get_float_uchar #define ncx_get_int_double vtk_netcdf_ncx_get_int_double #define ncx_get_int_float vtk_netcdf_ncx_get_int_float #define ncx_get_int_int vtk_netcdf_ncx_get_int_int #define ncx_get_int_long vtk_netcdf_ncx_get_int_long #define ncx_get_int_schar vtk_netcdf_ncx_get_int_schar #define ncx_get_int_short vtk_netcdf_ncx_get_int_short #define ncx_get_int_uchar vtk_netcdf_ncx_get_int_uchar #define ncx_getn_double_double vtk_netcdf_ncx_getn_double_double #define ncx_getn_double_float vtk_netcdf_ncx_getn_double_float #define ncx_getn_double_int vtk_netcdf_ncx_getn_double_int #define ncx_getn_double_long vtk_netcdf_ncx_getn_double_long #define ncx_getn_double_schar vtk_netcdf_ncx_getn_double_schar #define ncx_getn_double_short vtk_netcdf_ncx_getn_double_short #define ncx_getn_double_uchar vtk_netcdf_ncx_getn_double_uchar #define ncx_getn_float_double vtk_netcdf_ncx_getn_float_double #define ncx_getn_float_float vtk_netcdf_ncx_getn_float_float #define ncx_getn_float_int vtk_netcdf_ncx_getn_float_int #define ncx_getn_float_long vtk_netcdf_ncx_getn_float_long #define ncx_getn_float_schar vtk_netcdf_ncx_getn_float_schar #define ncx_getn_float_short vtk_netcdf_ncx_getn_float_short #define ncx_getn_float_uchar vtk_netcdf_ncx_getn_float_uchar #define ncx_getn_int_double vtk_netcdf_ncx_getn_int_double #define ncx_getn_int_float vtk_netcdf_ncx_getn_int_float #define ncx_getn_int_int vtk_netcdf_ncx_getn_int_int #define ncx_getn_int_long vtk_netcdf_ncx_getn_int_long #define ncx_getn_int_schar vtk_netcdf_ncx_getn_int_schar #define ncx_getn_int_short vtk_netcdf_ncx_getn_int_short #define ncx_getn_int_uchar vtk_netcdf_ncx_getn_int_uchar #define ncx_getn_schar_double vtk_netcdf_ncx_getn_schar_double #define ncx_getn_schar_float vtk_netcdf_ncx_getn_schar_float #define ncx_getn_schar_int vtk_netcdf_ncx_getn_schar_int #define ncx_getn_schar_long vtk_netcdf_ncx_getn_schar_long #define ncx_getn_schar_schar vtk_netcdf_ncx_getn_schar_schar #define ncx_getn_schar_short vtk_netcdf_ncx_getn_schar_short #define ncx_getn_schar_uchar vtk_netcdf_ncx_getn_schar_uchar #define ncx_getn_short_double vtk_netcdf_ncx_getn_short_double #define ncx_getn_short_float vtk_netcdf_ncx_getn_short_float #define ncx_getn_short_int vtk_netcdf_ncx_getn_short_int #define ncx_getn_short_long vtk_netcdf_ncx_getn_short_long #define ncx_getn_short_schar vtk_netcdf_ncx_getn_short_schar #define ncx_getn_short_short vtk_netcdf_ncx_getn_short_short #define ncx_getn_short_uchar vtk_netcdf_ncx_getn_short_uchar #define ncx_getn_text vtk_netcdf_ncx_getn_text #define ncx_getn_void vtk_netcdf_ncx_getn_void #define ncx_get_off_t vtk_netcdf_ncx_get_off_t #define ncx_get_short_double vtk_netcdf_ncx_get_short_double #define ncx_get_short_float vtk_netcdf_ncx_get_short_float #define ncx_get_short_int vtk_netcdf_ncx_get_short_int #define ncx_get_short_long vtk_netcdf_ncx_get_short_long #define ncx_get_short_schar vtk_netcdf_ncx_get_short_schar #define ncx_get_short_short vtk_netcdf_ncx_get_short_short #define ncx_get_short_uchar vtk_netcdf_ncx_get_short_uchar #define ncx_get_size_t vtk_netcdf_ncx_get_size_t #define ncx_howmany vtk_netcdf_ncx_howmany #define ncx_len_NC vtk_netcdf_ncx_len_NC #define ncx_pad_getn_schar_double vtk_netcdf_ncx_pad_getn_schar_double #define ncx_pad_getn_schar_float vtk_netcdf_ncx_pad_getn_schar_float #define ncx_pad_getn_schar_int vtk_netcdf_ncx_pad_getn_schar_int #define ncx_pad_getn_schar_long vtk_netcdf_ncx_pad_getn_schar_long #define ncx_pad_getn_schar_schar vtk_netcdf_ncx_pad_getn_schar_schar #define ncx_pad_getn_schar_short vtk_netcdf_ncx_pad_getn_schar_short #define ncx_pad_getn_schar_uchar vtk_netcdf_ncx_pad_getn_schar_uchar #define ncx_pad_getn_short_double vtk_netcdf_ncx_pad_getn_short_double #define ncx_pad_getn_short_float vtk_netcdf_ncx_pad_getn_short_float #define ncx_pad_getn_short_int vtk_netcdf_ncx_pad_getn_short_int #define ncx_pad_getn_short_long vtk_netcdf_ncx_pad_getn_short_long #define ncx_pad_getn_short_schar vtk_netcdf_ncx_pad_getn_short_schar #define ncx_pad_getn_short_short vtk_netcdf_ncx_pad_getn_short_short #define ncx_pad_getn_short_uchar vtk_netcdf_ncx_pad_getn_short_uchar #define ncx_pad_getn_text vtk_netcdf_ncx_pad_getn_text #define ncx_pad_getn_void vtk_netcdf_ncx_pad_getn_void #define ncx_pad_putn_schar_double vtk_netcdf_ncx_pad_putn_schar_double #define ncx_pad_putn_schar_float vtk_netcdf_ncx_pad_putn_schar_float #define ncx_pad_putn_schar_int vtk_netcdf_ncx_pad_putn_schar_int #define ncx_pad_putn_schar_long vtk_netcdf_ncx_pad_putn_schar_long #define ncx_pad_putn_schar_schar vtk_netcdf_ncx_pad_putn_schar_schar #define ncx_pad_putn_schar_short vtk_netcdf_ncx_pad_putn_schar_short #define ncx_pad_putn_schar_uchar vtk_netcdf_ncx_pad_putn_schar_uchar #define ncx_pad_putn_short_double vtk_netcdf_ncx_pad_putn_short_double #define ncx_pad_putn_short_float vtk_netcdf_ncx_pad_putn_short_float #define ncx_pad_putn_short_int vtk_netcdf_ncx_pad_putn_short_int #define ncx_pad_putn_short_long vtk_netcdf_ncx_pad_putn_short_long #define ncx_pad_putn_short_schar vtk_netcdf_ncx_pad_putn_short_schar #define ncx_pad_putn_short_short vtk_netcdf_ncx_pad_putn_short_short #define ncx_pad_putn_short_uchar vtk_netcdf_ncx_pad_putn_short_uchar #define ncx_pad_putn_text vtk_netcdf_ncx_pad_putn_text #define ncx_pad_putn_void vtk_netcdf_ncx_pad_putn_void #define ncx_put_double_double vtk_netcdf_ncx_put_double_double #define ncx_put_double_float vtk_netcdf_ncx_put_double_float #define ncx_put_double_int vtk_netcdf_ncx_put_double_int #define ncx_put_double_long vtk_netcdf_ncx_put_double_long #define ncx_put_double_schar vtk_netcdf_ncx_put_double_schar #define ncx_put_double_short vtk_netcdf_ncx_put_double_short #define ncx_put_double_uchar vtk_netcdf_ncx_put_double_uchar #define ncx_put_float_double vtk_netcdf_ncx_put_float_double #define ncx_put_float_float vtk_netcdf_ncx_put_float_float #define ncx_put_float_int vtk_netcdf_ncx_put_float_int #define ncx_put_float_long vtk_netcdf_ncx_put_float_long #define ncx_put_float_schar vtk_netcdf_ncx_put_float_schar #define ncx_put_float_short vtk_netcdf_ncx_put_float_short #define ncx_put_float_uchar vtk_netcdf_ncx_put_float_uchar #define ncx_put_int_double vtk_netcdf_ncx_put_int_double #define ncx_put_int_float vtk_netcdf_ncx_put_int_float #define ncx_put_int_int vtk_netcdf_ncx_put_int_int #define ncx_put_int_long vtk_netcdf_ncx_put_int_long #define ncx_put_int_schar vtk_netcdf_ncx_put_int_schar #define ncx_put_int_short vtk_netcdf_ncx_put_int_short #define ncx_put_int_uchar vtk_netcdf_ncx_put_int_uchar #define ncx_put_NC vtk_netcdf_ncx_put_NC #define ncx_putn_double_double vtk_netcdf_ncx_putn_double_double #define ncx_putn_double_float vtk_netcdf_ncx_putn_double_float #define ncx_putn_double_int vtk_netcdf_ncx_putn_double_int #define ncx_putn_double_long vtk_netcdf_ncx_putn_double_long #define ncx_putn_double_schar vtk_netcdf_ncx_putn_double_schar #define ncx_putn_double_short vtk_netcdf_ncx_putn_double_short #define ncx_putn_double_uchar vtk_netcdf_ncx_putn_double_uchar #define ncx_putn_float_double vtk_netcdf_ncx_putn_float_double #define ncx_putn_float_float vtk_netcdf_ncx_putn_float_float #define ncx_putn_float_int vtk_netcdf_ncx_putn_float_int #define ncx_putn_float_long vtk_netcdf_ncx_putn_float_long #define ncx_putn_float_schar vtk_netcdf_ncx_putn_float_schar #define ncx_putn_float_short vtk_netcdf_ncx_putn_float_short #define ncx_putn_float_uchar vtk_netcdf_ncx_putn_float_uchar #define ncx_putn_int_double vtk_netcdf_ncx_putn_int_double #define ncx_putn_int_float vtk_netcdf_ncx_putn_int_float #define ncx_putn_int_int vtk_netcdf_ncx_putn_int_int #define ncx_putn_int_long vtk_netcdf_ncx_putn_int_long #define ncx_putn_int_schar vtk_netcdf_ncx_putn_int_schar #define ncx_putn_int_short vtk_netcdf_ncx_putn_int_short #define ncx_putn_int_uchar vtk_netcdf_ncx_putn_int_uchar #define ncx_putn_schar_double vtk_netcdf_ncx_putn_schar_double #define ncx_putn_schar_float vtk_netcdf_ncx_putn_schar_float #define ncx_putn_schar_int vtk_netcdf_ncx_putn_schar_int #define ncx_putn_schar_long vtk_netcdf_ncx_putn_schar_long #define ncx_putn_schar_schar vtk_netcdf_ncx_putn_schar_schar #define ncx_putn_schar_short vtk_netcdf_ncx_putn_schar_short #define ncx_putn_schar_uchar vtk_netcdf_ncx_putn_schar_uchar #define ncx_putn_short_double vtk_netcdf_ncx_putn_short_double #define ncx_putn_short_float vtk_netcdf_ncx_putn_short_float #define ncx_putn_short_int vtk_netcdf_ncx_putn_short_int #define ncx_putn_short_long vtk_netcdf_ncx_putn_short_long #define ncx_putn_short_schar vtk_netcdf_ncx_putn_short_schar #define ncx_putn_short_short vtk_netcdf_ncx_putn_short_short #define ncx_putn_short_uchar vtk_netcdf_ncx_putn_short_uchar #define ncx_putn_text vtk_netcdf_ncx_putn_text #define ncx_putn_void vtk_netcdf_ncx_putn_void #define ncx_put_off_t vtk_netcdf_ncx_put_off_t #define ncx_put_short_double vtk_netcdf_ncx_put_short_double #define ncx_put_short_float vtk_netcdf_ncx_put_short_float #define ncx_put_short_int vtk_netcdf_ncx_put_short_int #define ncx_put_short_long vtk_netcdf_ncx_put_short_long #define ncx_put_short_schar vtk_netcdf_ncx_put_short_schar #define ncx_put_short_short vtk_netcdf_ncx_put_short_short #define ncx_put_short_uchar vtk_netcdf_ncx_put_short_uchar #define ncx_put_size_t vtk_netcdf_ncx_put_size_t #define ncx_szof vtk_netcdf_ncx_szof #define new_NC_string vtk_netcdf_new_NC_string #define new_x_NC_attr vtk_netcdf_new_x_NC_attr #define new_x_NC_dim vtk_netcdf_new_x_NC_dim #define new_x_NC_var vtk_netcdf_new_x_NC_var #define read_numrecs vtk_netcdf_read_numrecs #define set_NC_string vtk_netcdf_set_NC_string #define write_numrecs vtk_netcdf_write_numrecs #include "ncconfig.h" #endif /* vtk_netcdf_mangle_h */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/ncconfig.h.in0000755000175000017500000000743011606020250023033 0ustar amckinstryamckinstry/* libsrc/ncconfig.in. Generated automatically from configure.in by autoheader. */ /* $Id: ncconfig.h.in,v 1.1 2010-01-06 16:34:05 kwleiter Exp $ */ #ifndef _NCCONFIG_H_ #define _NCCONFIG_H_ /* Define if this is a shared build */ #cmakedefine BUILD_SHARED_LIBS #if defined( BUILD_SHARED_LIBS ) && defined( _WIN32 ) # define DLL_NETCDF #endif #ifdef vtkNetCDF_EXPORTS # define DLL_EXPORT #endif /* Define if you're on an HP-UX system. */ #cmakedefine _HPUX_SOURCE /* Define if type char is unsigned and you are not using gcc. */ #ifndef __CHAR_UNSIGNED__ #cmakedefine __CHAR_UNSIGNED__ #endif /* Define if your struct stat has st_blksize. */ #cmakedefine HAVE_ST_BLKSIZE @HAVE_ST_BLKSIZE@ /* Define to `long' if doesn't define. */ #cmakedefine off_t @off_t@ /* Define to `unsigned' if doesn't define. */ #cmakedefine size_t @size_t@ /* Define if you have the ANSI C header files. */ #cmakedefine STDC_HEADERS @STDC_HEADERS@ /* Define if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel and VAX). */ /* All compilers that support Mac OS X define either __BIG_ENDIAN__ or __LITTLE_ENDIAN__ to match the endianness of the architecture being compiled for. This is not necessarily the same as the architecture of the machine doing the building. In order to support Universal Binaries on Mac OS X, we prefer those defines to decide the endianness. On other platforms we use the result of the TRY_RUN. */ #if !defined(__APPLE__) #cmakedefine WORDS_BIGENDIAN @WORDS_BIGENDIAN@ #elif defined(__BIG_ENDIAN__) # define WORDS_BIGENDIAN 1 #endif /* Define if you don't have the . */ #cmakedefine NO_STDLIB_H @NO_STDLIB_H@ /* Define if you don't have the . */ #cmakedefine NO_SYS_TYPES_H @NO_SYS_TYPES_H@ /* Define if you have the ftruncate function */ #cmakedefine HAVE_FTRUNCATE @HAVE_FTRUNCATE@ /* Define if you have alloca, as a function or macro. */ #cmakedefine HAVE_ALLOCA @HAVE_ALLOCA@ /* Define if you have and it should be used (not on Ultrix). */ #cmakedefine HAVE_ALLOCA_H @HAVE_ALLOCA_H@ /* Define if you have and it should be used (not on Ultrix). */ #cmakedefine HAVE_UNISTD_H @HAVE_UNISTD_H@ /* Define if you don't have the strerror function */ #cmakedefine NO_STRERROR @NO_STRERROR@ /* Define to `int' if system doesn't define. */ #cmakedefine ssize_t @ssize_t@ /* Define to `int' if system doesn't define. */ #cmakedefine ptrdiff_t @ptrdiff_t@ /* Define to `unsigned char' if system doesn't define. */ #cmakedefine uchar @uchar@ /* Define if the system does not use IEEE floating point representation */ #cmakedefine NO_IEEE_FLOAT @NO_IEEE_FLOAT@ /* Size of fundamental data types. */ /* Mac OS X uses two data models, ILP32 (in which integers, long integers, and pointers are 32-bit quantities) and LP64 (in which integers are 32-bit quantities and long integers and pointers are 64-bit quantities). In order to support Universal Binaries on Mac OS X, we rely on this knowledge instead of testing the sizes of the building machine. On other platforms we use the result of the TRY_RUN. */ #if !defined(__APPLE__) #cmakedefine SIZEOF_SHORT @SIZEOF_SHORT@ #cmakedefine SIZEOF_INT @SIZEOF_INT@ #cmakedefine SIZEOF_LONG @SIZEOF_LONG@ #cmakedefine SIZEOF_FLOAT @SIZEOF_FLOAT@ #cmakedefine SIZEOF_DOUBLE @SIZEOF_DOUBLE@ #cmakedefine SIZEOF_SIZE_T @SIZEOF_SIZE_T@ #cmakedefine SIZEOF_OFF_T @SIZEOF_OFF_T@ #else # define SIZEOF_SHORT 2 # define SIZEOF_INT 4 # if defined(__LP64__) && __LP64__ # define SIZEOF_LONG 8 # define SIZEOF_SIZE_T 8 # else # define SIZEOF_LONG 4 # define SIZEOF_SIZE_T 4 # endif # define SIZEOF_FLOAT 4 # define SIZEOF_DOUBLE 8 # define SIZEOF_OFF_T 8 #endif #endif /* !_NCCONFIG_H_ */ xdmf-2.1.dfsg.1/Utilities/vtknetcdf/vtk_netcdf.h0000755000175000017500000000132011606020250022757 0ustar amckinstryamckinstry/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtk_netcdf.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __vtk_netcdf_h #define __vtk_netcdf_h /* Use the netcdf library configured for VTK. */ #include #endif xdmf-2.1.dfsg.1/Utilities/vtkexodus2/0000755000175000017500000000000011606020250020606 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtkexodus2/expcon.c0000755000175000017500000000777511606020250022271 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expcon - ex_put_coord_names * * entry conditions - * input parameters: * int exoid exodus file id * char* coord_names ptr array of coordinate names * * exit conditions - * * revision history - * * $Id: expcon.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the names of the coordinate arrays to the database * \param exoid exodus file id * \param coord_names ptr array of coordinate names */ int ex_put_coord_names (int exoid, char *coord_names[]) { int status; int i, ndimdim, varid; size_t num_dim, start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_NUM_DIM, &ndimdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of dimensions in file id %d", exoid); ex_err("ex_put_coord_names",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, ndimdim, &num_dim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: inquire failed to get number of dimensions in file id %d", exoid); ex_err("ex_put_coord_names",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_varid(exoid, VAR_NAME_COOR, &varid)) == -1) { exerrval = status; sprintf(errmsg, "Error: failed to locate coordinate names in file id %d", exoid); ex_err("ex_put_coord_names",errmsg,exerrval); return (EX_FATAL); } /* write out coordinate names */ for (i=0; i<(int)num_dim; i++) { start[0] = i; start[1] = 0; count[0] = 1; count[1] = strlen(coord_names[i]) + 1; if ((status = nc_put_vara_text(exoid, varid, start, count, coord_names[i])) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store coordinate name %d in file id %d", i,exoid); ex_err("ex_put_coord_names",errmsg,exerrval); return (EX_FATAL); } } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exclos.c0000755000175000017500000001020611606020250022251 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exclos - ex_close * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * * revision history - * * $Id: exclos.c,v 1.1 2010-01-06 16:33:04 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" extern char *ret_string; /* cf ex_utils.c */ /*! * updates and then closes an open EXODUS II file */ int ex_close (int exoid) { char errmsg[MAX_ERR_LENGTH]; int status; exerrval = 0; /* clear error code */ if ((status = nc_sync(exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to update file id %d",exoid); ex_err("ex_close",errmsg,exerrval); return(EX_FATAL); } /* Check header size. Will print message if too big... */ ex_header_size(exoid); if ((status = nc_close (exoid)) == NC_NOERR) { ex_conv_exit(exoid); ex_rm_file_item(exoid, ex_get_counter_list(EX_ELEM_BLOCK)); ex_rm_file_item(exoid, ex_get_counter_list(EX_FACE_BLOCK)); ex_rm_file_item(exoid, ex_get_counter_list(EX_EDGE_BLOCK)); ex_rm_file_item(exoid, ex_get_counter_list(EX_NODE_SET)); ex_rm_file_item(exoid, ex_get_counter_list(EX_EDGE_SET)); ex_rm_file_item(exoid, ex_get_counter_list(EX_FACE_SET)); ex_rm_file_item(exoid, ex_get_counter_list(EX_SIDE_SET)); ex_rm_file_item(exoid, ex_get_counter_list(EX_ELEM_SET)); ex_rm_file_item(exoid, ex_get_counter_list(EX_NODE_MAP)); ex_rm_file_item(exoid, ex_get_counter_list(EX_EDGE_MAP)); ex_rm_file_item(exoid, ex_get_counter_list(EX_FACE_MAP)); ex_rm_file_item(exoid, ex_get_counter_list(EX_ELEM_MAP)); ex_rm_stat_ptr (exoid, &exoII_ed); ex_rm_stat_ptr (exoid, &exoII_fa); ex_rm_stat_ptr (exoid, &exoII_eb); ex_rm_stat_ptr (exoid, &exoII_ns); ex_rm_stat_ptr (exoid, &exoII_es); ex_rm_stat_ptr (exoid, &exoII_fs); ex_rm_stat_ptr (exoid, &exoII_ss); ex_rm_stat_ptr (exoid, &exoII_els); ex_rm_stat_ptr (exoid, &exoII_nm); ex_rm_stat_ptr (exoid, &exoII_edm); ex_rm_stat_ptr (exoid, &exoII_fam); ex_rm_stat_ptr (exoid, &exoII_em); } else { exerrval = status; sprintf(errmsg, "Error: failed to close file id %d",exoid); ex_err("ex_close",errmsg, status); return(EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exinq.c0000755000175000017500000006061311606020250022107 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exinq - ex_inquire * * entry conditions - * input parameters: * int exoid exodus file id * int req_info info request code * * exit conditions - * int* ret_int returned integer value * float* ret_float returned float value * char* ret_char returned character value * * revision history - * * $Id: exinq.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" #define EX_GET_DIMENSION_VALUE(VAR,DEFVAL,DNAME,MISSINGOK) \ if ((status = nc_inq_dimid( exoid, DNAME, &dimid)) != NC_NOERR) { \ *VAR = DEFVAL; \ if ( MISSINGOK ) { \ return (EX_NOERR); \ } else { \ exerrval = status; \ sprintf( errmsg, \ "Error: failed to retrieve dimension " DNAME " for file id %d", \ exoid); \ ex_err("ex_inquire",errmsg,exerrval); \ return (EX_FATAL); \ } \ } \ if ((status = nc_inq_dimlen( exoid, dimid, &idum)) != NC_NOERR) { \ *VAR = DEFVAL; \ exerrval = status; \ sprintf( errmsg, \ "Error: failed to retrieve value for dimension " DNAME " for file id %d", \ exoid); \ ex_err("ex_inquire",errmsg,exerrval); \ return (EX_FATAL); \ } \ *VAR = idum; #define EX_GET_CONCAT_SET_LEN(VAR,TNAME,SETENUM,DNUMSETS,VSETSTAT,DSETSIZE,MISSINGOK) \ *ret_int = 0; /* default return value */ \ \ if ((status = nc_inq_dimid (exoid, DNUMSETS, &dimid)) == NC_NOERR) \ { \ if ((status = nc_inq_dimlen (exoid, dimid, &num_sets)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to get number of " TNAME " sets in file id %d", \ exoid); \ ex_err("ex_inquire",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ if (!(ids = malloc(num_sets*sizeof(int)))) { \ exerrval = EX_MEMFAIL; \ sprintf(errmsg, \ "Error: failed to allocate memory for " TNAME " set ids for file id %d", \ exoid); \ ex_err("ex_inquire",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ if (ex_get_ids (exoid, SETENUM, ids) == EX_FATAL) { \ sprintf(errmsg, \ "Error: failed to get " TNAME " set ids in file id %d", \ exoid); \ ex_err("ex_inquire",errmsg,exerrval); \ free(ids); \ return (EX_FATAL); \ } \ \ /* allocate space for stat array */ \ if (!(stat_vals = malloc((int)num_sets*sizeof(int)))) { \ exerrval = EX_MEMFAIL; \ free (ids); \ sprintf(errmsg, \ "Error: failed to allocate memory for " TNAME " set status array for file id %d", \ exoid); \ ex_err("ex_inquire",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ /* get variable id of status array */ \ if ((status = nc_inq_varid (exoid, VSETSTAT, &varid)) == NC_NOERR) { \ /* if status array exists, use it, otherwise assume, object exists \ to be backward compatible */ \ if ((status = nc_get_var_int(exoid, varid, stat_vals)) != NC_NOERR) { \ exerrval = status; \ free (ids); \ free(stat_vals); \ sprintf(errmsg, \ "Error: failed to get " TNAME " set status array from file id %d", \ exoid); \ ex_err("ex_inquire",errmsg,exerrval); \ return (EX_FATAL); \ } \ } else /* default: status is true */ \ for(i=0;i #include "exodusII.h" #include "exodusII_int.h" /*! * reads the connectivity array for an element block * \deprecated Use ex_get_conn()(exoid, EX_ELEM_BLOCK, elem_blk_id, connect, 0, 0) instead */ int ex_get_elem_conn (int exoid, int elem_blk_id, int *connect) { return ex_get_conn( exoid, EX_ELEM_BLOCK, elem_blk_id, connect, 0, 0 ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exptim.c0000755000175000017500000000705711606020250022274 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exptim - ex_put_time * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * float time_value simulation time at specified step * * exit conditions - * * revision history - * * $Id: exptim.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the time value for a whole time step; * assume the first time step is 1 * \param exoid exodus file id * \param time_step time step number (1...) * \param time_value simulation time at specified step */ int ex_put_time (int exoid, int time_step, const void *time_value) { int status; int varid; size_t start[1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined variable */ if ((status = nc_inq_varid(exoid, VAR_WHOLE_TIME, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate time variable in file id %d", exoid); ex_err("ex_put_time",errmsg,exerrval); return (EX_FATAL); } /* store time value */ start[0] = --time_step; if (ex_comp_ws(exoid) == 4) { status = nc_put_var1_float(exoid, varid, start, time_value); } else { status = nc_put_var1_double(exoid, varid, start, time_value); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store time value in file id %d", exoid); ex_err("ex_put_time",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expidm.c0000644000175000017500000001275311606020250022250 0ustar amckinstryamckinstry/* * Copyright (c) 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expenm - ex_put_id_map * * entry conditions - * input parameters: * int exoid exodus file id * ex_entity_type obj_type * int* elem_map element numbering map array * * exit conditions - * * revision history - * * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /* for free() */ /*! * writes out the entity numbering map to the database; this allows * the entity numbers to be non-contiguous. This map is used for * mapping between local and global entity ids. * \param exoid exodus file id * \param map_type * \param map element numbering map array */ int ex_put_id_map (int exoid, ex_entity_type map_type, const int *map) { int dimid, mapid, status, dims[1]; char errmsg[MAX_ERR_LENGTH]; const char* tname; const char* dnumentries; const char* vmap; exerrval = 0; /* clear error code */ switch ( map_type ) { case EX_NODE_MAP: tname = "node"; dnumentries = DIM_NUM_NODES; vmap = VAR_NODE_NUM_MAP; break; case EX_EDGE_MAP: tname = "edge"; dnumentries = DIM_NUM_EDGE; vmap = VAR_EDGE_NUM_MAP; break; case EX_FACE_MAP: tname = "face"; dnumentries = DIM_NUM_FACE; vmap = VAR_FACE_NUM_MAP; break; case EX_ELEM_MAP: tname = "element"; dnumentries = DIM_NUM_ELEM; vmap = VAR_ELEM_NUM_MAP; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Bad map type (%d) specified for file id %d", map_type, exoid ); ex_err( "ex_put_id_map", errmsg, exerrval ); return (EX_FATAL); } /* Make sure the file contains entries */ if (nc_inq_dimid (exoid, dnumentries, &dimid) != NC_NOERR) { return (EX_NOERR); } /* put netcdf file into define mode */ if (nc_inq_varid (exoid, vmap, &mapid) != NC_NOERR) { if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_id_map",errmsg,exerrval); return (EX_FATAL); } /* create a variable array in which to store the id map */ dims[0] = dimid; if ((status = nc_def_var(exoid, vmap, NC_INT, 1, dims, &mapid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: %s numbering map already exists in file id %d", tname, exoid); ex_err("ex_put_id_map",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to create %s id map in file id %d", tname, exoid); ex_err("ex_put_id_map",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete definition in file id %d", exoid); ex_err("ex_put_id_map",errmsg,exerrval); return (EX_FATAL); } } /* write out the entity numbering map */ status = nc_put_var_int(exoid, mapid, map); if (status!= NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s numbering map in file id %d", tname, exoid); ex_err("ex_put_id_map",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_id_map",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expinix.c0000644000175000017500000005147111606020250022446 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expinix - ex_put_init_ext * * entry conditions - * input parameters: * int exoid exodus file id * const ex_init_params* params finite element model parameters * * exit conditions - * * revision history - * David Thompson - Added edge/face blocks/sets * * $Id: expinix.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include #include #include #define EX_WRITE_OBJECT_PARAMS(TNAME,DNAME,SNAME,INAME,NUM_BLK,DIMVAR) \ /* Can have nonzero model->num_elem_blk even if model->num_elem == 0 */ \ if ((NUM_BLK) > 0) { \ if ((status = nc_def_dim(exoid, DNAME, (size_t)(NUM_BLK), &DIMVAR)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define number of " TNAME "s in file id %d", \ exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ /* ...and some variables */ \ /* element block id status array */ \ dim[0] = DIMVAR; \ if ((status = nc_def_var (exoid, SNAME, NC_INT, 1, dim, &varid)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define " TNAME " status array in file id %d",exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ \ /* TNAME id array */ \ if ((status = nc_def_var (exoid, INAME, NC_INT, 1, dim, &varid)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define " TNAME " id array in file id %d",exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ \ /* store property name as attribute of property array variable */ \ if ((status=nc_put_att_text(exoid, varid, ATT_PROP_NAME, 3, "ID")) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to store " TNAME " property name %s in file id %d", \ "ID",exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ return (EX_FATAL); \ } \ } #define EX_WRITE_MAP_PARAMS(TNAME,DNUMMAP,VMAPIDS,NUMMAPS,MAPDIM) \ /* Can have nonzero model->num_XXXX_map even if model->num_XXXX == 0 */ \ if ((NUMMAPS) > 0) { \ if ((status = nc_def_dim(exoid, DNUMMAP, (size_t)(NUMMAPS), &MAPDIM)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define number of " TNAME "s in file id %d", \ exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ \ dim[0] = MAPDIM; \ \ /* TNAME id array */ \ if ((status = nc_def_var(exoid, VMAPIDS, NC_INT, 1, dim, &varid)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define " TNAME " id array in file id %d",exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ \ /* store property name as attribute of property array variable */ \ if ((status=nc_put_att_text(exoid, varid, ATT_PROP_NAME, 3, "ID")) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to store " TNAME " property name %s in file id %d", \ "ID",exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ return (EX_FATAL); \ } \ } #define EX_WRITE_OBJECT_NAMES(TNAME,DNAME,DIMVAR,DIMVAL) \ /* Element block names... */ \ if ((DIMVAL) > 0) { \ dim[0] = (DIMVAR); \ dim[1] = strdim; \ \ if ((status = nc_def_var (exoid, DNAME, NC_CHAR, 2, dim, &varid)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define %s name array in file id %d",TNAME,exoid); \ ex_err("ex_put_init_ext",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ } static void zero_id_status(int exoid, const char *var_stat, const char *var_id, int count, int *ids) { int status; int i; int id_var, stat_var; if (count > 0) { for (i=0; i < count; i++) { ids[i] = 0; } status = nc_inq_varid(exoid, var_id, &id_var); assert(status == NC_NOERR); status = nc_inq_varid(exoid, var_stat, &stat_var); assert(status == NC_NOERR); status = nc_put_var_int(exoid, id_var, ids); assert(status == NC_NOERR); status = nc_put_var_int(exoid, stat_var, ids); assert(status == NC_NOERR); } } /*! * writes the initialization parameters to the EXODUS II file * \param exoid exodus file id * \param model finite element model parameters */ int ex_put_init_ext (int exoid, const ex_init_params *model) { int numdimdim, numnoddim, elblkdim, edblkdim, fablkdim, esetdim, fsetdim, elsetdim, nsetdim, ssetdim, strdim, dim[2], varid, temp; int status; int nmapdim,edmapdim,famapdim,emapdim; int title_len; #if 0 /* used for header size calculations which are turned off for now */ int header_size, fixed_var_size, iows; #endif char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ if (nc_inq_dimid (exoid, DIM_NUM_DIM, &temp) == NC_NOERR) { exerrval = EX_MSG; sprintf(errmsg, "Error: initialization already done for file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); return (EX_FATAL); } /* put file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_init_ext",errmsg,exerrval); return (EX_FATAL); } /* define some attributes... */ title_len = strlen(model->title) < MAX_LINE_LENGTH ? strlen(model->title) : MAX_LINE_LENGTH; if ((status = nc_put_att_text(exoid, NC_GLOBAL, (const char*)ATT_TITLE, title_len+1, model->title)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define model->title attribute to file id %d", exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* ...and some dimensions... */ if ((status = nc_def_dim(exoid, DIM_NUM_DIM, model->num_dim, &numdimdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of dimensions in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* * Need to handle "empty file" that may be the result of a strange * load balance or some other strange run. Note that if num_node * == 0, then model->num_elem must be zero since you cannot have elements * with no nodes. It *is* permissible to have zero elements with * non-zero node count. */ if (model->num_nodes > 0) { if ((status = nc_def_dim(exoid, DIM_NUM_NODES, model->num_nodes, &numnoddim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of nodes in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (model->num_elem > 0) { if (model->num_nodes <= 0) { exerrval = EX_MSG; sprintf(errmsg, "Error: Cannot have non-zero element count if node count is zero.in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ((status = nc_def_dim(exoid, DIM_NUM_ELEM, model->num_elem, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of elements in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (model->num_edge > 0) { if (model->num_nodes <= 0) { exerrval = EX_MSG; sprintf(errmsg, "Error: Cannot have non-zero edge count if node count is zero.in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ((status = nc_def_dim(exoid, DIM_NUM_EDGE, model->num_edge, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of edges in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (model->num_face > 0) { if (model->num_nodes <= 0) { exerrval = EX_MSG; sprintf(errmsg, "Error: Cannot have non-zero face count if node count is zero.in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ((status = nc_def_dim(exoid, DIM_NUM_FACE, model->num_face, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of faces in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } EX_WRITE_OBJECT_PARAMS("element block", DIM_NUM_EL_BLK, VAR_STAT_EL_BLK, VAR_ID_EL_BLK, model->num_elem_blk, elblkdim); EX_WRITE_OBJECT_PARAMS("edge block", DIM_NUM_ED_BLK, VAR_STAT_ED_BLK, VAR_ID_ED_BLK, model->num_edge_blk, edblkdim); EX_WRITE_OBJECT_PARAMS("face block", DIM_NUM_FA_BLK, VAR_STAT_FA_BLK, VAR_ID_FA_BLK, model->num_face_blk, fablkdim); EX_WRITE_OBJECT_PARAMS("node set", DIM_NUM_NS, VAR_NS_STAT, VAR_NS_IDS, model->num_node_sets, nsetdim); EX_WRITE_OBJECT_PARAMS("edge set", DIM_NUM_ES, VAR_ES_STAT, VAR_ES_IDS, model->num_edge_sets, esetdim); EX_WRITE_OBJECT_PARAMS("face set", DIM_NUM_FS, VAR_FS_STAT, VAR_FS_IDS, model->num_face_sets, fsetdim); EX_WRITE_OBJECT_PARAMS("side set", DIM_NUM_SS, VAR_SS_STAT, VAR_SS_IDS, model->num_side_sets, ssetdim); EX_WRITE_OBJECT_PARAMS("elem set", DIM_NUM_ELS, VAR_ELS_STAT, VAR_ELS_IDS, model->num_elem_sets, elsetdim); EX_WRITE_MAP_PARAMS( "node map", DIM_NUM_NM, VAR_NM_PROP(1), model->num_node_maps, nmapdim); EX_WRITE_MAP_PARAMS( "edge map", DIM_NUM_EDM, VAR_EDM_PROP(1), model->num_edge_maps, edmapdim); EX_WRITE_MAP_PARAMS( "face map", DIM_NUM_FAM, VAR_FAM_PROP(1), model->num_face_maps, famapdim); EX_WRITE_MAP_PARAMS("element map", DIM_NUM_EM, VAR_EM_PROP(1), model->num_elem_maps, emapdim); /* * To reduce the maximum dataset sizes, the storage of the nodal * coordinates and the nodal variables was changed from a single * dataset to a dataset per component or variable. However, we * want to maintain some form of compatability with the old * exodusII version. It is easy to do this on read; however, we * also want to be able to store in the old format using the new * library. * * The mode is set in the ex_create call. The setting can be checked * via the ATT_FILESIZE attribute in the file (1=large, * 0=normal). Also handle old files that do not contain this * attribute. */ if (model->num_nodes > 0) { if (ex_large_model(exoid) == 1) { /* node coordinate arrays -- separate storage... */ dim[0] = numnoddim; if (model->num_dim > 0) { if ((status = nc_def_var (exoid, VAR_COORD_X, nc_flt_code(exoid), 1, dim, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define node x coordinate array in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (model->num_dim > 1) { if ((status = nc_def_var(exoid, VAR_COORD_Y, nc_flt_code(exoid), 1, dim, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define node y coordinate array in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (model->num_dim > 2) { if ((status = nc_def_var(exoid, VAR_COORD_Z, nc_flt_code(exoid), 1, dim, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define node z coordinate array in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } else { /* node coordinate arrays: -- all stored together (old method) */ dim[0] = numdimdim; dim[1] = numnoddim; if ((status = nc_def_var(exoid, VAR_COORD, nc_flt_code(exoid), 2, dim, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define node coordinate array in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } /* inquire previously defined dimensions */ if ((status = nc_inq_dimid (exoid, DIM_STR, &strdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* coordinate names array */ dim[0] = numdimdim; dim[1] = strdim; if ((status=nc_def_var(exoid, VAR_NAME_COOR, NC_CHAR, 2, dim, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define coordinate name array in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } EX_WRITE_OBJECT_NAMES("element block",VAR_NAME_EL_BLK,elblkdim,model->num_elem_blk); EX_WRITE_OBJECT_NAMES("edge block", VAR_NAME_ED_BLK,edblkdim,model->num_edge_blk); EX_WRITE_OBJECT_NAMES("face block", VAR_NAME_FA_BLK,fablkdim,model->num_face_blk); EX_WRITE_OBJECT_NAMES("node set", VAR_NAME_NS, nsetdim, model->num_node_sets); EX_WRITE_OBJECT_NAMES("edge set", VAR_NAME_ES, esetdim, model->num_edge_sets); EX_WRITE_OBJECT_NAMES("face set", VAR_NAME_FS, fsetdim, model->num_face_sets); EX_WRITE_OBJECT_NAMES("side set", VAR_NAME_SS, ssetdim, model->num_side_sets); EX_WRITE_OBJECT_NAMES("element set", VAR_NAME_ELS, elsetdim,model->num_elem_sets); EX_WRITE_OBJECT_NAMES("node map", VAR_NAME_NM, nmapdim, model->num_node_maps); EX_WRITE_OBJECT_NAMES("edge map", VAR_NAME_EDM, edmapdim,model->num_edge_maps); EX_WRITE_OBJECT_NAMES("face map", VAR_NAME_FAM, famapdim,model->num_face_maps); EX_WRITE_OBJECT_NAMES("element map", VAR_NAME_EM, emapdim, model->num_elem_maps); /* leave define mode */ #if 1 if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete variable definitions in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); return (EX_FATAL); } #else /* estimate (guess) size of header of netCDF file */ header_size = 1200 + model->num_elem_blk * 800 + model->num_node_sets * 220 + model->num_side_sets * 300; if (header_size > MAX_HEADER_SIZE) header_size = MAX_HEADER_SIZE; /* estimate (guess) size of fixed size variable section of netCDF file */ if (nc_flt_code(exoid) == NC_DOUBLE) iows = 8; else iows = 4; fixed_var_size = model->num_dim * model->num_nodes * iows + model->num_nodes * sizeof(int) + model->num_elem * 16 * sizeof(int) + model->num_elem_blk * sizeof(int) + model->num_node_sets * model->num_nodes/100 * sizeof(int) + model->num_node_sets * model->num_nodes/100 * iows + model->num_node_sets * sizeof(int) + model->num_side_sets * model->num_elem/100 * 2 * sizeof(int) + model->num_side_sets * model->num_elem/100 * iows + model->num_side_sets * sizeof(int); /* With netcdf-3.4, this produces very large files on the * SGI. Also with netcdf-3.5beta3 */ /* * This is also causing other problems on other systems .. disable for now */ if ((status = nc__enddef (exoid, header_size, NC_ALIGN_CHUNK, fixed_var_size, NC_ALIGN_CHUNK)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete variable definitions in file id %d",exoid); ex_err("ex_put_init_ext",errmsg,exerrval); return (EX_FATAL); } #endif /* Fill the id and status arrays with zeros */ { int *zeros = NULL; int maxset = model->num_elem_blk; if (maxset < model->num_elem_blk) maxset = model->num_elem_blk; if (maxset < model->num_edge_blk) maxset = model->num_edge_blk; if (maxset < model->num_face_blk) maxset = model->num_face_blk; if (maxset < model->num_node_sets) maxset = model->num_node_sets; if (maxset < model->num_edge_sets) maxset = model->num_edge_sets; if (maxset < model->num_face_sets) maxset = model->num_face_sets; if (maxset < model->num_side_sets) maxset = model->num_side_sets; if (maxset < model->num_elem_sets) maxset = model->num_elem_sets; /* allocate space for id/status array */ if (!(zeros = malloc(maxset*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate memory for id/status array for file id %d", exoid); ex_err("ex_put_init_ext",errmsg,exerrval); return (EX_FATAL); } zero_id_status(exoid, VAR_STAT_EL_BLK, VAR_ID_EL_BLK, model->num_elem_blk, zeros); zero_id_status(exoid, VAR_STAT_ED_BLK, VAR_ID_ED_BLK, model->num_edge_blk, zeros); zero_id_status(exoid, VAR_STAT_FA_BLK, VAR_ID_FA_BLK, model->num_face_blk, zeros); zero_id_status(exoid, VAR_NS_STAT, VAR_NS_IDS, model->num_node_sets, zeros); zero_id_status(exoid, VAR_ES_STAT, VAR_ES_IDS, model->num_edge_sets, zeros); zero_id_status(exoid, VAR_FS_STAT, VAR_FS_IDS, model->num_face_sets, zeros); zero_id_status(exoid, VAR_SS_STAT, VAR_SS_IDS, model->num_side_sets, zeros); zero_id_status(exoid, VAR_ELS_STAT, VAR_ELS_IDS, model->num_elem_sets, zeros); if (zeros != NULL) { free(zeros); zeros = NULL; } } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_init_ext",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/.NoDartCoverage0000644000175000017500000000004711606020250023453 0ustar amckinstryamckinstry# do not do coverage in this directory xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exopen.c0000755000175000017500000001607511606020250022264 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exopen - ex_open * * entry conditions - * input parameters: * char* path exodus filename path * int mode access mode w/r * * exit conditions - * int exoid exodus file id * int* comp_ws computer word size * int* io_ws storage word size * float* version EXODUSII interface version number * * revision history - * * $Id: exopen.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * opens an existing EXODUS II file (or EXODUS II history file) and returns * an id that can subsequently be used to refer to the file. Multiple files * may be open simultaneously. * \param path exodus filename path * \param mode access mode w/r * \param[out] comp_ws computer word size * \param[out] io_ws storage word size * \param[out] version EXODUSII interface version number * \param run_version EXODUSII version number of linked library * \return exoid exodus file id */ int ex_open_int (const char *path, int mode, int *comp_ws, int *io_ws, float *version, int run_version) { int exoid; int status; int old_fill; int file_wordsize; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* set error handling mode to no messages, non-fatal errors */ ex_opts(exoptval); /* call required to set ncopts first time through */ if (run_version != EX_API_VERS_NODOT) { int run_version_major = run_version / 100; int run_version_minor = run_version % 100; int lib_version_major = EX_API_VERS_NODOT / 100; int lib_version_minor = EX_API_VERS_NODOT % 100; fprintf(stderr, "EXODUSII: Warning: This code was compiled with exodusII version %d.%02d,\n but was linked with exodusII library version %d.%02d\n This is probably an error in the build process of this code.\n", run_version_major, run_version_minor, lib_version_major, lib_version_minor); } if (mode == EX_READ) { /* READ ONLY */ #if defined(__LIBCATAMOUNT__) if ((status = nc_open (path, NC_NOWRITE, &exoid)) != NC_NOERR) #else if ((status = nc_open (path, NC_NOWRITE|NC_SHARE, &exoid)) != NC_NOERR) #endif { /* NOTE: netCDF returns an id of -1 on an error - but no error code! */ if (status == 0) exerrval = EX_FATAL; else exerrval = status; sprintf(errmsg,"Error: failed to open %s read only",path); ex_err("ex_open",errmsg,exerrval); return(EX_FATAL); } } else if (mode == EX_WRITE) /* READ/WRITE */ { #if defined(__LIBCATAMOUNT__) if ((status = nc_open (path, NC_WRITE, &exoid)) != NC_NOERR) #else if ((status = nc_open (path, NC_WRITE|NC_SHARE, &exoid)) != NC_NOERR) #endif { /* NOTE: netCDF returns an id of -1 on an error - but no error code! */ if (status == 0) exerrval = EX_FATAL; else exerrval = status; sprintf(errmsg,"Error: failed to open %s write only",path); ex_err("ex_open",errmsg,exerrval); return(EX_FATAL); } /* turn off automatic filling of netCDF variables */ if ((status = nc_set_fill (exoid, NC_NOFILL, &old_fill)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to set nofill mode in file id %d", exoid); ex_err("ex_open", errmsg, exerrval); return (EX_FATAL); } } else { exerrval = EX_BADFILEMODE; sprintf(errmsg,"Error: invalid file open mode: %d",mode); ex_err("ex_open",errmsg,exerrval); return (EX_FATAL); } /* determine version of EXODUS II file, and the word size of * floating point values stored in the file */ if ((status = nc_get_att_float(exoid, NC_GLOBAL, ATT_VERSION, version)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to get database version for file id: %d", exoid); ex_err("ex_open",errmsg,exerrval); return(EX_FATAL); } /* check ExodusII file version - old version 1.x files are not supported */ if (*version < 2.0) { exerrval = EX_FATAL; sprintf(errmsg,"Error: Unsupported file version %.2f in file id: %d", *version, exoid); ex_err("ex_open",errmsg,exerrval); return(EX_FATAL); } if (nc_get_att_int (exoid, NC_GLOBAL, ATT_FLT_WORDSIZE, &file_wordsize) != NC_NOERR) { /* try old (prior to db version 2.02) attribute name */ if (nc_get_att_int (exoid,NC_GLOBAL,ATT_FLT_WORDSIZE_BLANK,&file_wordsize) != NC_NOERR) { exerrval = EX_FATAL; sprintf(errmsg,"Error: failed to get file wordsize from file id: %d", exoid); ex_err("ex_open",errmsg,exerrval); return(exerrval); } } /* initialize floating point size conversion. */ if (ex_conv_ini( exoid, comp_ws, io_ws, file_wordsize ) != EX_NOERR ) { exerrval = EX_FATAL; sprintf(errmsg, "Error: failed to init conversion routines in file id %d", exoid); ex_err("ex_open", errmsg, exerrval); return (EX_FATAL); } return (exoid); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgelb.c0000755000175000017500000000602711606020250022230 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgelb - read element block parameters * * entry conditions - * input parameters: * int idexo exodus file id * int elem_blk_id element block id * * exit conditions - * char* elem_type element type name * int* num_elem_this_blk number of elements in this element block * int* num_nodes_per_elem number of nodes per element block * int* num_attr number of attributes * * revision history - * * $Id: exgelb.c,v 1.1 2010-01-06 16:33:07 kwleiter Exp $ * */ #include #include #include "exodusII.h" #include "exodusII_int.h" /** * reads the parameters used to describe an element block * \deprecated Use ex_get_block()(exoid, EX_ELEM_BLOCK, elem_blk_id, elem_type, num_elem_this_blk, num_nodes_per_elem, num_attr) instead */ int ex_get_elem_block (int exoid, int elem_blk_id, char *elem_type, int *num_elem_this_blk, int *num_nodes_per_elem, int *num_attr) { return ex_get_block( exoid, EX_ELEM_BLOCK, elem_blk_id, elem_type, num_elem_this_blk, num_nodes_per_elem, 0, 0, num_attr ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expns.c0000755000175000017500000000544211606020250022117 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expns - ex_put_node_set * * entry conditions - * input parameters: * int exoid exodus file id * int node_set_id node set id * int* node_set_node_list node list array for the node set * * exit conditions - * * revision history - * * $Id: expns.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the node list for a single node set * \param exoid exodus file id * \param node_set_id node set id * \param node_set_node_list node list array for the node set * \deprecated Use ex_put_set()(exoid, EX_NODE_SET, node_set_id, node_set_node_list, NULL) */ int ex_put_node_set (int exoid, int node_set_id, const int *node_set_node_list) { return ex_put_set(exoid, EX_NODE_SET, node_set_id, node_set_node_list, NULL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgini.c0000755000175000017500000000771111606020250022246 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgini - ex_get_init * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * char* title title of file * int* num_dim number of dimensions (per node) * int* num_nodes number of nodes * int* num_elem number of elements * int* num_elem_blk number of element blocks * int* num_node_sets number of node sets * int* num_side_sets numver of side sets * * revision history - * David Thompson - Moved to exginix.c (exgini.c now a special case) * * $Id: exgini.c,v 1.1 2010-01-06 16:33:12 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * reads the initialization parameters from an opened EXODUS II file * \param exoid exodus file id * \param[out] title Title of the mesh, String length may be up to #MAX_LINE_LENGTH characters. * \param[out] num_dim Dimensionality of the database. This is the number of coordinates per node. * \param[out] num_nodes Number of nodes * \param[out] num_elem Number of elements * \param[out] num_elem_blk Number of element blocks * \param[out] num_node_sets Number of node sets * \param[out] num_side_sets Number of side sets * \sa ex_get_init_ext() */ int ex_get_init (int exoid, char *title, int *num_dim, int *num_nodes, int *num_elem, int *num_elem_blk, int *num_node_sets, int *num_side_sets) { ex_init_params info; int errval; info.title[0] = '\0'; errval = ex_get_init_ext( exoid, &info ); if ( errval < 0 ) { return errval; } *num_dim = info.num_dim; *num_nodes = info.num_nodes; *num_elem = info.num_elem; *num_elem_blk = info.num_elem_blk; *num_node_sets = info.num_node_sets; *num_side_sets = info.num_side_sets; strcpy( title, info.title ); return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expeat.c0000755000175000017500000000534711606020250022254 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expeat - ex_put_elem_attr * * entry conditions - * input parameters: * int exoid exodus file id * int elem_blk_id element block id * float* attrib array of attributes * * exit conditions - * * revision history - * * $Id: expeat.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the attributes for an element block * \param exoid exodus file id * \param elem_blk_id element block id * \param attrib array of attributes * \deprecated Use ex_put_attr()(exoid, EX_ELEM_BLOCK, elem_blk_id, attrib) */ int ex_put_elem_attr (int exoid, int elem_blk_id, const void *attrib) { return ex_put_attr( exoid, EX_ELEM_BLOCK, elem_blk_id, attrib ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expev.c0000755000175000017500000000670711606020250022116 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expev - ex_put_elem_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int elem_var_index element variable index * int elem_blk_id element block id * int num_elem_this_blk number of elements in this block * * exit conditions - * * * exit conditions - * * revision history - * * $Id: expev.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of a single element variable for one element block at * one time step to the database; assume the first time step and * element variable index are 1 * \param exoid exodus file id * \param time_step time step number * \param elem_var_index element variable index * \param elem_blk_id element block id * \param num_elem_this_blk number of elements in this block * \param elem_var_vals the element bariables to be written * \deprecated Use ex_put_var()(exoid, time_step, EX_ELEM_BLOCK, elem_var_index, elem_blk_id, num_elem_this_blk, elem_var_vals) */ int ex_put_elem_var (int exoid, int time_step, int elem_var_index, int elem_blk_id, int num_elem_this_blk, const void *elem_var_vals) { return ex_put_var(exoid, time_step, EX_ELEM_BLOCK, elem_var_index, elem_blk_id, num_elem_this_blk, elem_var_vals); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvar.c0000644000175000017500000001232711606020250022253 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgev - ex_get_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * ex_entity_type var_type block/variable type * node, edge/face/element block, or * node/edge/face/side/element set * int var_index variable index * int obj_id object id * int num_entry_this_obj number of entries in this object * * * exit conditions - * float* var_vals array of element variable values * * * revision history - * 20061002 - David Thompson - Adapted from ex_get_elem_var * * $Id: exgvar.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the values of a single element variable for one element block at * one time step in the database; assume the first time step and * element variable index is 1 */ int ex_get_var( int exoid, int time_step, ex_entity_type var_type, int var_index, int obj_id, int num_entry_this_obj, void* var_vals ) { int status; int varid, obj_id_ndx; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; if (var_type == EX_NODAL) { /* FIXME: Special case: ignore obj_id, possible large_file complications, etc. */ return ex_get_nodal_var( exoid, time_step, var_index, num_entry_this_obj, var_vals ); } else if (var_type == EX_GLOBAL) { /* FIXME: Special case: all vars stored in 2-D single array. */ return ex_get_glob_vars( exoid, time_step, num_entry_this_obj, var_vals ); } exerrval = 0; /* clear error code */ /* Determine index of obj_id in VAR_ID_EL_BLK array */ obj_id_ndx = ex_id_lkup(exoid,var_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no %s variables for NULL block %d in file id %d", ex_name_of_object(var_type), obj_id,exoid); ex_err("ex_get_var",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate %s id %d in id variable in file id %d", ex_name_of_object(var_type), obj_id, exoid); ex_err("ex_get_var",errmsg,exerrval); return (EX_FATAL); } } /* inquire previously defined variable */ if((status = nc_inq_varid(exoid, ex_name_var_of_object(var_type,var_index, obj_id_ndx), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s %d var %d in file id %d", ex_name_of_object(var_type),obj_id,var_index,exoid); ex_err("ex_get_var",errmsg,exerrval); return (EX_FATAL); } /* read values of element variable */ start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_entry_this_obj; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s %d variable %d in file id %d", ex_name_of_object(var_type), obj_id, var_index,exoid); ex_err("ex_get_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvart.c0000644000175000017500000002556311606020250022445 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvart - ex_get_var_time * * entry conditions - * input parameters: * int exoid exodus file id * int var_type variable type global, nodal, * edge/face/elem block, * node/edge/face/side/elem set * int var_index element variable index * int id entry number * int beg_time_step time step number * int end_time_step time step number * * exit conditions - * float* var_vals array of element variable values * * revision history - * 20061002 - David Thompson - Adapted from ex_get_var_time * * $Id: exgvart.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the values of a variable for a single entry of an object (block or set) through a * specified number of time steps in the database; assume the first * variable index, entry number, and time step are 1 */ int ex_get_var_time( int exoid, ex_entity_type var_type, int var_index, int id, int beg_time_step, int end_time_step, void* var_vals ) { int i, dimid, varid, numel = 0, offset; int status; int *obj_ids, *stat_vals; size_t num_obj; size_t num_entries_this_obj = 0; size_t start[2], count[2]; float fdum; char *cdum; char errmsg[MAX_ERR_LENGTH]; const char* varobjids; const char* varobstat; switch (var_type) { case EX_GLOBAL: return ex_get_glob_var_time( exoid, var_index, beg_time_step, end_time_step, var_vals ); case EX_NODAL: return ex_get_nodal_var_time( exoid, var_index, id, beg_time_step, end_time_step, var_vals ); case EX_EDGE_BLOCK: varobjids = VAR_ID_ED_BLK; varobstat = VAR_STAT_ED_BLK; break; case EX_FACE_BLOCK: varobjids = VAR_ID_FA_BLK; varobstat = VAR_STAT_FA_BLK; break; case EX_ELEM_BLOCK: varobjids = VAR_ID_EL_BLK; varobstat = VAR_STAT_EL_BLK; break; case EX_NODE_SET: varobjids = VAR_NS_IDS; varobstat = VAR_NS_STAT; break; case EX_EDGE_SET: varobjids = VAR_ES_IDS; varobstat = VAR_ES_STAT; break; case EX_FACE_SET: varobjids = VAR_FS_IDS; varobstat = VAR_FS_STAT; break; case EX_SIDE_SET: varobjids = VAR_SS_IDS; varobstat = VAR_SS_STAT; break; case EX_ELEM_SET: varobjids = VAR_ELS_IDS; varobstat = VAR_ELS_STAT; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Invalid variable type (%d) specified for file id %d", var_type, exoid ); ex_err( "ex_get_var_time", errmsg, exerrval ); return (EX_FATAL); } exerrval = 0; /* clear error code */ cdum = 0; /* initialize even though it is not used */ /* assume entry number is 1-based (the first entry of an object is 1, not 0); * adjust so it is 0-based */ id--; /* find what object the entry is in */ /* first, find out how many objects there are */ status = ex_get_dimension(exoid, ex_dim_num_objects(var_type), ex_name_of_object(var_type), &num_obj, &dimid, "ex_get_var_time"); if (status != NC_NOERR) return status; /* get the array of object ids */ /* don't think we need this anymore since the netcdf variable names associated with objects don't contain the object ids */ if (!(obj_ids = malloc(num_obj*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate memory for %s ids for file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_varid (exoid, varobjids, &varid )) != NC_NOERR) { exerrval = status; free(obj_ids); sprintf(errmsg, "Error: failed to locate %s ids in file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_get_var_int(exoid, varid, obj_ids)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s ids from file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } /* allocate space for stat array */ if (!(stat_vals = malloc((int)num_obj*sizeof(int)))) { exerrval = EX_MEMFAIL; free (obj_ids); sprintf(errmsg, "Error: failed to allocate memory for %s status array for file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } /* get variable id of status array */ if (nc_inq_varid (exoid, varobstat, &varid) == NC_NOERR) { /* if status array exists, use it, otherwise assume, object exists to be backward compatible */ if ((status = nc_get_var_int(exoid, varid, stat_vals)) != NC_NOERR) { exerrval = status; free (obj_ids); free(stat_vals); sprintf(errmsg, "Error: failed to get %s status array from file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } } else { /* default: status is true */ for(i=0;i<(int)num_obj;i++) stat_vals[i]=1; } /* loop through each object until id is found; since entry * numbers are sequential (beginning with 1) id is in obj_i * when id_first_i <= id <= id_last_i, where * id_first_i is the entry number of the first entry in * obj_i and id_last_i is the entry number of the last * entry in obj_i */ i = 0; if (stat_vals[i] != 0) { if ((status = nc_inq_dimid(exoid, ex_dim_num_entries_in_object(var_type,i+1), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of entries in %s %d in file id %d", ex_name_of_object(var_type), obj_ids[i], exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); free(obj_ids); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, &num_entries_this_obj)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of entries in %s %d in file id %d", ex_name_of_object(var_type), obj_ids[i], exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); free(obj_ids); return (EX_FATAL); } } /* End NULL object check */ numel = num_entries_this_obj; while (numel <= id) { if (stat_vals[++i] != 0) { if ((status = nc_inq_dimid(exoid,ex_dim_num_entries_in_object(var_type,i+1), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of entries in %s %d in file id %d", ex_name_of_object(var_type), obj_ids[i], exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); free(obj_ids); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, &num_entries_this_obj)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of entries in %s %d in file id %d", ex_name_of_object(var_type), obj_ids[i], exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); free(obj_ids); return (EX_FATAL); } numel += num_entries_this_obj; } } offset = id - (numel - num_entries_this_obj); /* inquire previously defined variable */ if ((status = nc_inq_varid(exoid,ex_name_var_of_object(var_type,var_index,i+1), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate variable %d for %s %d in file id %d", var_index,ex_name_of_object(var_type),obj_ids[i],exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); free(obj_ids); return (EX_FATAL); } free(stat_vals); free(obj_ids); /* read values of object variable */ start[0] = --beg_time_step; start[1] = offset; if (end_time_step < 0) { /* user is requesting the maximum time step; we find this out using the * database inquire function to get the number of time steps; the ending * time step number is 1 less due to 0 based array indexing in C */ if ((status = ex_inquire (exoid, EX_INQ_TIME, &end_time_step, &fdum, cdum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get maximum time step in file id %d", exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } } end_time_step--; count[0] = end_time_step - beg_time_step + 1; count[1] = 1; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s variable values in file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvnm.c0000755000175000017500000000545011606020250022265 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvnm - ex_get_var_name * * entry conditions - * input parameters: * int exoid exodus file id * char* var_type variable type: G,N, or E * int var_num variable index to read 1..num_var * * exit conditions - * char* var_name ptr to variable name * * revision history - * * $Id: exgvnm.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the name of a particular results variable from the database * \deprecated use ex_get_variable_name()(exoid, obj_type, var_num, *var_name) */ int ex_get_var_name (int exoid, const char *var_type, int var_num, char *var_name) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return ex_get_variable_name(exoid, obj_type, var_num, var_name); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvartab.c0000644000175000017500000001554011606020250022742 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvtt - ex_get_truth_table * * entry conditions - * input parameters: * int exoid exodus file id * int num_blk number of blocks * int num_var number of variables * * exit conditions - * int* var_tab element variable truth table array * * $Id: exgvartab.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" #include /*! * reads the EXODUS II specified variable truth table from the database */ int ex_get_truth_table (int exoid, ex_entity_type obj_type, int num_blk, int num_var, int *var_tab) { int dimid, varid, tabid, i, j, status, status1; size_t num_entity = 0; size_t num_var_db = 0; char errmsg[MAX_ERR_LENGTH]; const char* routine = "ex_get_truth_table"; /* * The ent_type and the var_name are used to build the netcdf * variables name. Normally this is done via a macro defined in * exodusII_int.h */ const char* ent_type = NULL; const char* var_name = NULL; exerrval = 0; /* clear error code */ switch (obj_type) { case EX_EDGE_BLOCK: status = ex_get_dimension(exoid, DIM_NUM_EDG_VAR, "edge variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_EBLK_TAB, &tabid); var_name = "vals_edge_var"; ent_type = "eb"; break; case EX_FACE_BLOCK: status = ex_get_dimension(exoid, DIM_NUM_FAC_VAR, "face variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_FBLK_TAB, &tabid); var_name = "vals_face_var"; ent_type = "fb"; break; case EX_ELEM_BLOCK: status = ex_get_dimension(exoid, DIM_NUM_ELE_VAR, "element variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_ELEM_TAB, &tabid); var_name = "vals_elem_var"; ent_type = "eb"; break; case EX_NODE_SET: status = ex_get_dimension(exoid, DIM_NUM_NSET_VAR, "nodeset variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_NSET_TAB, &tabid); var_name = "vals_nset_var"; ent_type = "ns"; break; case EX_EDGE_SET: status = ex_get_dimension(exoid, DIM_NUM_ESET_VAR, "edgeset variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_ESET_TAB, &tabid); var_name = "vals_eset_var"; ent_type = "es"; break; case EX_FACE_SET: status = ex_get_dimension(exoid, DIM_NUM_FSET_VAR, "faceset variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_FSET_TAB, &tabid); var_name = "vals_fset_var"; ent_type = "fs"; break; case EX_SIDE_SET: status = ex_get_dimension(exoid, DIM_NUM_SSET_VAR, "sideset variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_SSET_TAB, &tabid); var_name = "vals_sset_var"; ent_type = "ss"; break; case EX_ELEM_SET: status = ex_get_dimension(exoid, DIM_NUM_ELSET_VAR, "elemset variables", &num_var_db, &varid, routine); status1 = nc_inq_varid (exoid, VAR_ELSET_TAB, &tabid); var_name = "vals_elset_var"; ent_type = "es"; break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid variable type %d specified in file id %d", obj_type, exoid); ex_err(routine,errmsg,exerrval); return (EX_WARN); } if (status != NC_NOERR) { exerrval = status; return (EX_WARN); } status = ex_get_dimension(exoid, ex_dim_num_objects(obj_type), ex_name_of_object(obj_type), &num_entity, &dimid, routine); if (status != NC_NOERR) { exerrval = status; return (EX_FATAL); } if (num_entity != (size_t)num_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: # of %s doesn't match those defined in file id %d", ex_name_of_object(obj_type), exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } if (num_var_db != (size_t)num_var) { exerrval = EX_FATAL; sprintf(errmsg, "Error: # of %s variables doesn't match those defined in file id %d", ex_name_of_object(obj_type), exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } if (status1 != NC_NOERR) { /* since truth table isn't stored in the data file, derive it dynamically */ for (j=0; j #include "exodusII.h" #include "exodusII_int.h" /*! * reads the EXODUS II specified variable truth vector from the database */ int ex_get_object_truth_vector (int exoid, ex_entity_type obj_type, int entity_id, int num_var, int *var_vec) { int statust; int varid, tabid, i, status, ent_ndx; size_t num_var_db = 0; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; const char* routine = "ex_get_object_truth_vector"; /* * The ent_type and the var_name are used to build the netcdf * variables name. Normally this is done via a macro defined in * exodusII_int.h */ const char* ent_type = NULL; const char* var_name = NULL; exerrval = 0; /* clear error code */ switch (obj_type) { case EX_EDGE_BLOCK: status = ex_get_dimension(exoid, DIM_NUM_EDG_VAR, "edge variables", &num_var_db, &varid, routine); statust = nc_inq_varid(exoid, VAR_EBLK_TAB, &tabid); var_name = "vals_edge_var"; ent_type = "eb"; break; case EX_FACE_BLOCK: status = ex_get_dimension(exoid, DIM_NUM_FAC_VAR, "face variables", &num_var_db, &varid, routine); statust = nc_inq_varid (exoid, VAR_FBLK_TAB, &tabid); var_name = "vals_face_var"; ent_type = "fb"; break; case EX_ELEM_BLOCK: status = ex_get_dimension(exoid, DIM_NUM_ELE_VAR, "element variables", &num_var_db, &varid, routine); statust = nc_inq_varid (exoid, VAR_ELEM_TAB, &tabid); var_name = "vals_elem_var"; ent_type = "eb"; break; case EX_NODE_SET: status = ex_get_dimension(exoid, DIM_NUM_NSET_VAR, "nodeset variables", &num_var_db, &varid, routine); statust = nc_inq_varid (exoid, VAR_NSET_TAB, &tabid); var_name = "vals_nset_var"; ent_type = "ns"; break; case EX_EDGE_SET: status = ex_get_dimension(exoid, DIM_NUM_ESET_VAR, "edgeset variables", &num_var_db, &varid, routine); statust = nc_inq_varid (exoid, VAR_ESET_TAB, &tabid); var_name = "vals_eset_var"; ent_type = "es"; break; case EX_FACE_SET: status = ex_get_dimension(exoid, DIM_NUM_FSET_VAR, "faceset variables", &num_var_db, &varid, routine); statust = nc_inq_varid (exoid, VAR_FSET_TAB, &tabid); var_name = "vals_fset_var"; ent_type = "fs"; break; case EX_SIDE_SET: status = ex_get_dimension(exoid, DIM_NUM_SSET_VAR, "sideset variables", &num_var_db, &varid, routine); statust = nc_inq_varid (exoid, VAR_SSET_TAB, &tabid); var_name = "vals_sset_var"; ent_type = "ss"; break; case EX_ELEM_SET: status = ex_get_dimension(exoid, DIM_NUM_ELSET_VAR, "elemset variables", &num_var_db, &varid, routine); statust = nc_inq_varid (exoid, VAR_ELSET_TAB, &tabid); var_name = "vals_elset_var"; ent_type = "es"; break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid variable type %d specified in file id %d", obj_type, exoid); ex_err(routine,errmsg,exerrval); return (EX_WARN); } if (status != NC_NOERR) { exerrval = status; return (EX_WARN); } /* Determine index of entity_id in id array */ ent_ndx = ex_id_lkup(exoid,obj_type,entity_id); if (exerrval != 0) { if (exerrval != EX_NULLENTITY) { sprintf(errmsg, "Error: failed to locate %s id %d in id variable in file id %d", ex_name_of_object(obj_type), entity_id, exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } } /* If this is a null entity, then 'ent_ndx' will be negative. * We don't care in this routine, so make it positive and continue... */ if (ent_ndx < 0) ent_ndx = -ent_ndx; if ((int)num_var_db != num_var) { exerrval = EX_FATAL; sprintf(errmsg, "Error: # of variables doesn't match those defined in file id %d", exoid); ex_err("ex_get_object_truth_vector",errmsg,exerrval); return (EX_FATAL); } if (statust != NC_NOERR) { /* since truth vector isn't stored in the data file, derive it dynamically */ for (i=0; i #include "exodusII.h" #include "exodusII_int.h" /* * reads the connectivity array for an element block */ int ex_get_conn( int exoid, ex_entity_type blk_type, int blk_id, int* nodeconn, int* edgeconn, int* faceconn ) { int connid, econnid, fconnid, blk_id_ndx, status; int numnodperentdim, numedgperentdim, numfacperentdim; int iexit = (EX_NOERR); /* exit status */ size_t num_nodes_per_entry, num_edges_per_entry, num_faces_per_entry; char errmsg[MAX_ERR_LENGTH]; const char* dnumblkent; const char* dnumnodent; const char* dnumedgent; const char* dnumfacent; const char* vnodeconn; const char* vedgeconn; const char* vfaceconn; /* Should we warn if edgeconn or faceconn are non-NULL? * No, fail silently so the same code can be used to read any type of block info. * However, we will warn if edgeconn or faceconn are NULL but num_edges_per_entry * or num_faces_per_entry (respectively) are positive. */ exerrval = 0; /* clear error code */ /* Locate index of element block id in VAR_ID_EL_BLK array */ blk_id_ndx = ex_id_lkup(exoid,blk_type,blk_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no connectivity array for NULL %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg,EX_MSG); return (EX_WARN); /* no connectivity array for this element block */ } else { sprintf(errmsg, "Error: failed to locate %s id %d in id array in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg,exerrval); return (EX_FATAL); } } switch (blk_type) { case EX_EDGE_BLOCK: dnumblkent = DIM_NUM_ED_IN_EBLK(blk_id_ndx); dnumnodent = DIM_NUM_NOD_PER_ED(blk_id_ndx); dnumedgent = 0; dnumfacent = 0; vnodeconn = VAR_EBCONN(blk_id_ndx); vedgeconn = 0; vfaceconn = 0; break; case EX_FACE_BLOCK: dnumblkent = DIM_NUM_FA_IN_FBLK(blk_id_ndx); dnumnodent = DIM_NUM_NOD_PER_FA(blk_id_ndx); dnumedgent = 0; dnumfacent = 0; vnodeconn = VAR_FBCONN(blk_id_ndx); vedgeconn = 0; vfaceconn = 0; break; case EX_ELEM_BLOCK: dnumblkent = DIM_NUM_EL_IN_BLK(blk_id_ndx); dnumnodent = DIM_NUM_NOD_PER_EL(blk_id_ndx); dnumedgent = DIM_NUM_EDG_PER_EL(blk_id_ndx); dnumfacent = DIM_NUM_FAC_PER_EL(blk_id_ndx); vnodeconn = VAR_CONN(blk_id_ndx); vedgeconn = VAR_ECONN(blk_id_ndx); vfaceconn = VAR_FCONN(blk_id_ndx); break; default: sprintf(errmsg, "Error: Called with invalid blk_type %d", blk_type ); ex_err("ex_get_conn",errmsg,exerrval); return (EX_FATAL); break; } /* inquire id's of previously defined dimensions */ if ((status = nc_inq_dimid (exoid, dnumnodent, &numnodperentdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of nodes/entity for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg,exerrval); return(EX_FATAL); } if (nc_inq_dimlen(exoid, numnodperentdim, &num_nodes_per_entry) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of nodes/entity for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } if ( dnumedgent ) { num_edges_per_entry = 0; if ((status = nc_inq_dimid(exoid, dnumedgent, &numedgperentdim)) != NC_NOERR) { numedgperentdim = -1; } else { if ((status = nc_inq_dimlen(exoid, numedgperentdim, &num_edges_per_entry)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of edges/entry for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } } } if ( dnumfacent ) { num_faces_per_entry = 0; if ((status = nc_inq_dimid(exoid, dnumfacent, &numfacperentdim)) != NC_NOERR) { numfacperentdim = -1; } else { if ((status = nc_inq_dimlen(exoid, numfacperentdim, &num_faces_per_entry)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of faces/entry for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } } } if ((status = nc_inq_varid(exoid, vnodeconn, &connid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate connectivity array for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } status = 0; if (edgeconn && (numedgperentdim > 0) && ((status = nc_inq_varid (exoid, vedgeconn, &econnid)) != NC_NOERR)) { exerrval = status; sprintf(errmsg, "Error: failed to locate edge connectivity array for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } if (faceconn && (numfacperentdim > 0) && ((status = nc_inq_varid (exoid, vfaceconn, &fconnid)) != NC_NOERR)) { exerrval = status; sprintf(errmsg, "Error: failed to locate face connectivity array for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } /* read in the connectivity array */ if ( edgeconn && num_edges_per_entry > 0) { status = nc_get_var_int(exoid, econnid, edgeconn); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get edge connectivity array for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } } if ( faceconn && num_faces_per_entry > 0) { status = nc_get_var_int(exoid, fconnid, faceconn); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get face connectivity array for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } } if ( nodeconn && num_nodes_per_entry > 0) { status = nc_get_var_int(exoid, connid, nodeconn); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get connectivity array for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_conn",errmsg, exerrval); return(EX_FATAL); } } return iexit; } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnnm.c0000755000175000017500000000513711606020250022270 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnnm - ex_put_node_num_map * * entry conditions - * input parameters: * int exoid exodus file id * int* node_map node numbering map * * exit conditions - * * revision history - * * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /* for free() */ /*! * writes out the node numbering map to the database; allows node numbers * to be non-contiguous * \param exoid exodus file id * \param node_map node numbering map * \deprecated Use ex_put_id_map()(exoid, EX_NODE_MAP, node_map) */ int ex_put_node_num_map (int exoid, const int *node_map) { return ex_put_id_map(exoid, EX_NODE_MAP, node_map); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expsetd.c0000644000175000017500000001311411606020250022426 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expssd - ex_put_set_dist_fact * * entry conditions - * input parameters: * int exoid exodus file id * int set_type set type * int set_id set id * void* set_dist_fact array of dist factors for set * exit conditions - * * revision history - * * $Id: expsetd.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the distribution factors for a single set * \param exoid exodus file id * \param set_type set type * \param set_id set id * \param *set_dist_fact array of dist factors for set */ int ex_put_set_dist_fact (int exoid, ex_entity_type set_type, int set_id, const void *set_dist_fact) { int status; int dimid, set_id_ndx; int dist_id; char errmsg[MAX_ERR_LENGTH]; char* factptr = NULL; exerrval = 0; /* clear error code */ /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: no %ss specified in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_set_dist_fact",errmsg,exerrval); return (EX_FATAL); } /* Lookup index of set id in VAR_*S_IDS array */ set_id_ndx = ex_id_lkup(exoid,set_type,set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no data allowed for NULL %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_fact",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate %s id %d in VAR_*S_IDS array in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_dist_fact",errmsg,exerrval); return (EX_FATAL); } } /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */ factptr = VAR_FACT_NS(set_id_ndx); } else if (set_type == EX_EDGE_SET) { factptr = VAR_FACT_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { factptr = VAR_FACT_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { factptr = VAR_FACT_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { factptr = VAR_FACT_ELS(set_id_ndx); } /* find id of distribution factors variable */ if ((status = nc_inq_varid(exoid, factptr, &dist_id)) != NC_NOERR) { /* this test is only needed for node set because we're using DIM_NUM_NOD_NS instead of DIM_NUM_DF_NS*/ if (status == NC_ENOTVAR) { exerrval = EX_BADPARAM; sprintf(errmsg, "Warning: no dist factors defined for %s %d in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_put_set_dist_fact",errmsg,exerrval); return (EX_WARN); } else { exerrval = status; sprintf(errmsg, "Error: failed to locate dist factors list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_dist_fact",errmsg,exerrval); return (EX_FATAL); } } /* write out the distribution factors array */ if (ex_comp_ws(exoid) == 4) { status = nc_put_var_float(exoid, dist_id, set_dist_fact); } else { status = nc_put_var_double(exoid, dist_id, set_dist_fact); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store dist factors for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_dist_fact",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expcab.c0000644000175000017500000005326411606020250022226 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expclb - ex_put_concat_all_blocks: write elem, edge, & face block parameters * * entry conditions - * input parameters: * int exoid exodus file id * const ex_block_params* bparam block parameters structure * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the parameters used to describe all element, edge, and face blocks * \param exoid exodus file id * \param param block parameters structure */ int ex_put_concat_all_blocks (int exoid, const ex_block_params *param) { int varid, dimid, dims[2], strdim, *eb_stat, *ed_stat, *fa_stat; int temp; size_t iblk; int status; size_t i, num_elem_blk, num_edge_blk, num_face_blk; int cur_num_elem_blk, nelnoddim, numelbdim, numattrdim, connid=-1; int cur_num_edge_blk, numedbdim, nednoddim, cur_num_face_blk, numfabdim, nfanoddim; int neledgdim=-1, nelfacdim=-1; char errmsg[MAX_ERR_LENGTH]; int elem_work = 0; /* is DIM_NUM_EL_BLK defined? If so, there's work to do */ int edge_work = 0; /* is DIM_NUM_ED_BLK defined? If so, there's work to do */ int face_work = 0; /* is DIM_NUM_FA_BLK defined? If so, there's work to do */ static const char* dim_num_maps[] = { DIM_NUM_NM, DIM_NUM_EDM, DIM_NUM_FAM, DIM_NUM_EM, }; static const char* dim_size_maps[] = { DIM_NUM_NODES, DIM_NUM_EDGE, DIM_NUM_FACE, DIM_NUM_ELEM, }; static const ex_entity_type map_enums[] = { EX_NODE_MAP, EX_EDGE_MAP, EX_FACE_MAP, EX_ELEM_MAP }; /* If param->define_maps is true, we must fill these with values from ex_put_init_ext before entering define mode */ size_t num_maps[sizeof(dim_num_maps)/sizeof(dim_num_maps[0])]; size_t num_map_dims = sizeof(dim_num_maps)/sizeof(dim_num_maps[0]); exerrval = 0; /* clear error code */ /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_STR, &strdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); return (EX_FATAL); } if ( param->define_maps ) { for ( i = 0; i < num_map_dims; ++i ) { if ((status = nc_inq_dimid(exoid, dim_num_maps[i], &dimid)) != NC_NOERR) { exerrval = status; sprintf( errmsg, "Error: failed to find node map size of file id %d", exoid ); ex_err( "ex_put_concat_all_blocks", errmsg, exerrval ); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, num_maps+i)) != NC_NOERR) { exerrval = status; sprintf( errmsg, "Error: failed to retrieve node map size of file id %d", exoid ); ex_err( "ex_put_concat_all_blocks", errmsg, exerrval ); return (EX_FATAL); } } } #define EX_PREPARE_BLOCK(TNAME,WNAME,DNUMNAME,VSTATNAME,VIDNAME,LNUMNAME,SNUMNAME,SIDNAME,GSTAT) \ /* first check if any TNAME blocks are specified \ * OK if zero... \ */ \ if ((status = (nc_inq_dimid(exoid, DNUMNAME, &dimid))) == NC_NOERR) { \ WNAME = 1; \ \ /* Get number of TNAME blocks defined for this file */ \ if ((status = nc_inq_dimlen(exoid,dimid,&LNUMNAME)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to get number of " TNAME " blocks in file id %d", \ exoid); \ ex_err("ex_put_concat_all_blocks",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ /* Fill out the TNAME block status array */ \ if (!(GSTAT = malloc(LNUMNAME*sizeof(int)))) { \ exerrval = EX_MEMFAIL; \ sprintf(errmsg, \ "Error: failed to allocate space for " TNAME " block status array in file id %d", \ exoid); \ ex_err("ex_put_concat_all_blocks",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ for (i=0;inum_elem_this_blk,param->elem_blk_id,eb_stat); EX_PREPARE_BLOCK( "edge",edge_work,DIM_NUM_ED_BLK,VAR_STAT_ED_BLK,VAR_ID_ED_BLK, num_edge_blk,param->num_edge_this_blk,param->edge_blk_id,ed_stat); EX_PREPARE_BLOCK( "face",face_work,DIM_NUM_FA_BLK,VAR_STAT_FA_BLK,VAR_ID_FA_BLK, num_face_blk,param->num_face_this_blk,param->face_blk_id,fa_stat); if ( elem_work == 0 && edge_work == 0 && face_work == 0 && param->define_maps == 0 ) { /* Nothing to do. This is not an error, but we can save * ourselves from entering define mode by returning here. */ return (EX_NOERR); } /* put netcdf file into define mode */ if ((status = nc_redef(exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); return (EX_FATAL); } #define EX_PREPARE_ATTRIB_ARRAY(TNAME,CURBLK,DNAME,DVAL,ID,VANAME,VADIM0,VADIM1,VANNAME) \ if (DVAL[iblk] > 0) { \ if ((status = nc_def_dim (exoid, \ DNAME(CURBLK+1), \ DVAL[iblk], &VADIM1)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define number of attributes in " TNAME " block %d in file id %d", \ ID[iblk],exoid); \ ex_err("ex_put_concat_all_blocks",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ \ dims[0] = VADIM0; \ dims[1] = VADIM1; \ \ if ((status = nc_def_var (exoid, VANAME(CURBLK+1), \ nc_flt_code(exoid), 2, dims, &temp)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define attributes for " TNAME " block %d in file id %d", \ ID[iblk],exoid); \ ex_err("ex_put_concat_all_blocks",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ \ /* Attribute names... */ \ dims[0] = VADIM1; \ dims[1] = strdim; \ \ if ((status = nc_def_var(exoid, VANNAME(CURBLK+1), NC_CHAR, 2, dims, &temp)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define " TNAME " attribute name array in file id %d",exoid); \ ex_err("ex_put_concat_all_blocks",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ } #define EX_PREPARE_CONN(TNAME,BLK,BLKID,BLKSZ,VNAME,DNAME) \ if ( DNAME > 0 ) { \ dims[0] = BLKSZ; \ dims[1] = DNAME; \ \ if ((status = nc_def_var(exoid, VNAME(BLK+1), \ NC_INT, 2, dims, &connid)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to create " TNAME " connectivity array for block %d in file id %d", \ BLKID[iblk],exoid); \ ex_err("ex_put_concat_all_blocks",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ } /* Iterate over edge blocks ... */ for (iblk = 0; iblk < num_edge_blk; ++iblk) { cur_num_edge_blk=ex_get_file_item(exoid, ex_get_counter_list(EX_EDGE_BLOCK)); if (cur_num_edge_blk >= (int)num_edge_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of edge blocks (%ld) defined in file id %d", (long)(num_edge_blk),exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; } /* NOTE: ex_inc_file_item is used to find the number of edge blocks for a specific file and returns that value incremented. */ cur_num_edge_blk=ex_inc_file_item(exoid, ex_get_counter_list(EX_EDGE_BLOCK)); if (param->num_edge_this_blk[iblk] == 0) /* Is this a NULL edge block? */ continue; /* define some dimensions and variables*/ if ((status = nc_def_dim(exoid, DIM_NUM_ED_IN_EBLK(cur_num_edge_blk+1), param->num_edge_this_blk[iblk],&numedbdim)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { /* duplicate entry */ sprintf(errmsg, "Error: edge block %d already defined in file id %d", param->edge_blk_id[iblk],exoid); } else { sprintf(errmsg, "Error: failed to define number of edges/block for block %d file id %d", param->edge_blk_id[iblk],exoid); } ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ((status = nc_def_dim(exoid, DIM_NUM_NOD_PER_ED(cur_num_edge_blk+1), param->num_nodes_per_edge[iblk],&nednoddim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of nodes/edge for block %d in file id %d", param->edge_blk_id[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* edge attribute array */ EX_PREPARE_ATTRIB_ARRAY("edge",cur_num_edge_blk,DIM_NUM_ATT_IN_EBLK,param->num_attr_edge,param->edge_blk_id,VAR_EATTRIB,numedbdim,numattrdim,VAR_NAME_EATTRIB); EX_PREPARE_CONN("edge block",cur_num_edge_blk,param->edge_blk_id,numedbdim,VAR_EBCONN,nednoddim); /* store edge type as attribute of connectivity variable */ if ((status = nc_put_att_text(exoid, connid, ATT_NAME_ELB, strlen(param->edge_type[iblk])+1, (void*)param->edge_type[iblk])) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store edge type name %s in file id %d", param->edge_type[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* Iterate over face blocks ... */ for (iblk = 0; iblk < num_face_blk; ++iblk) { cur_num_face_blk=ex_get_file_item(exoid, ex_get_counter_list(EX_FACE_BLOCK)); if (cur_num_face_blk >= (int)num_face_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of face blocks (%ld) defined in file id %d", (long)num_face_blk,exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; } /* NOTE: ex_inc_file_item is used to find the number of edge blocks for a specific file and returns that value incremented. */ cur_num_face_blk=ex_inc_file_item(exoid, ex_get_counter_list(EX_FACE_BLOCK)); if (param->num_face_this_blk[iblk] == 0) /* Is this a NULL face block? */ continue; /* define some dimensions and variables*/ if ((status = nc_def_dim (exoid, DIM_NUM_FA_IN_FBLK(cur_num_face_blk+1), param->num_face_this_blk[iblk],&numfabdim)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { /* duplicate entry */ sprintf(errmsg, "Error: face block %d already defined in file id %d", param->face_blk_id[iblk],exoid); } else { sprintf(errmsg, "Error: failed to define number of faces/block for block %d file id %d", param->face_blk_id[iblk],exoid); } ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ((status = nc_def_dim (exoid, DIM_NUM_NOD_PER_FA(cur_num_face_blk+1), param->num_nodes_per_face[iblk],&nfanoddim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of nodes/face for block %d in file id %d", param->face_blk_id[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* edge attribute array */ EX_PREPARE_ATTRIB_ARRAY("face",cur_num_face_blk,DIM_NUM_ATT_IN_FBLK,param->num_attr_face,param->face_blk_id,VAR_FATTRIB,numfabdim,numattrdim,VAR_NAME_FATTRIB); EX_PREPARE_CONN("face block",cur_num_face_blk,param->face_blk_id,numfabdim,VAR_FBCONN,nfanoddim); /* store face type as attribute of connectivity variable */ if ((status = nc_put_att_text(exoid, connid, ATT_NAME_ELB, strlen(param->face_type[iblk])+1, (void*)param->face_type[iblk])) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store face type name %s in file id %d", param->face_type[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* Iterate over element blocks ... */ for (iblk = 0; iblk < num_elem_blk; ++iblk) { cur_num_elem_blk=ex_get_file_item(exoid, ex_get_counter_list(EX_ELEM_BLOCK)); if (cur_num_elem_blk >= (int)num_elem_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of element blocks (%ld) defined in file id %d", (long)num_elem_blk,exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; } /* NOTE: ex_inc_file_item is used to find the number of element blocks for a specific file and returns that value incremented. */ cur_num_elem_blk=ex_inc_file_item(exoid, ex_get_counter_list(EX_ELEM_BLOCK)); if (param->num_elem_this_blk[iblk] == 0) /* Is this a NULL element block? */ continue; /* define some dimensions and variables*/ if ((status = nc_def_dim (exoid, DIM_NUM_EL_IN_BLK(cur_num_elem_blk+1), param->num_elem_this_blk[iblk], &numelbdim)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { /* duplicate entry */ sprintf(errmsg, "Error: element block %d already defined in file id %d", param->elem_blk_id[iblk],exoid); } else { sprintf(errmsg, "Error: failed to define number of elements/block for block %d file id %d", param->elem_blk_id[iblk],exoid); } ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* Always define DIM_NUM_NOD_PER_EL, even if zero. * Do not define DIM_NUM_EDG_PER_EL or DIM_NUM_FAC_PER_EL unless > 0. */ if ((status = nc_def_dim (exoid, DIM_NUM_NOD_PER_EL(cur_num_elem_blk+1), param->num_nodes_per_elem[iblk], &nelnoddim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of nodes/element for block %d in file id %d", param->elem_blk_id[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ( param->num_edges_per_elem[iblk] > 0 ) { if ((status = nc_def_dim (exoid, DIM_NUM_EDG_PER_EL(cur_num_elem_blk+1), param->num_edges_per_elem[iblk],&neledgdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of edges/element for block %d in file id %d", param->elem_blk_id[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if ( param->num_faces_per_elem[iblk] > 0 ) { if ((status = nc_def_dim(exoid, DIM_NUM_FAC_PER_EL(cur_num_elem_blk+1), param->num_faces_per_elem[iblk],&nelfacdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of faces/element for block %d in file id %d", param->elem_blk_id[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* element attribute array */ EX_PREPARE_ATTRIB_ARRAY("element",cur_num_elem_blk,DIM_NUM_ATT_IN_BLK,param->num_attr_elem,param->elem_blk_id,VAR_ATTRIB,numelbdim,numattrdim,VAR_NAME_ATTRIB); /* element connectivity array */ EX_PREPARE_CONN("nodal",cur_num_elem_blk,param->elem_blk_id,numelbdim,VAR_CONN,nelnoddim); /* store element type as attribute of connectivity variable */ if ((status = nc_put_att_text(exoid, connid, ATT_NAME_ELB, strlen(param->elem_type[iblk])+1, (void*)param->elem_type[iblk])) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store element type name %s in file id %d", param->elem_type[iblk],exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } EX_PREPARE_CONN( "edge",cur_num_elem_blk,param->elem_blk_id,numelbdim,VAR_ECONN,neledgdim); EX_PREPARE_CONN( "face",cur_num_elem_blk,param->elem_blk_id,numelbdim,VAR_FCONN,nelfacdim); } /* Define the element map here to avoid a later redefine call */ if ( param->define_maps != 0 ) { size_t map_type; for ( map_type = 0; map_type < num_map_dims; ++map_type ) { if ((status = nc_inq_dimid(exoid, dim_size_maps[map_type], &dims[0])) != NC_NOERR) { exerrval = status; sprintf( errmsg, "Error: could not find map size dimension %s in file id %d", dim_size_maps[map_type], exoid ); ex_err( "ex_put_concat_all_blocks", errmsg, exerrval ); } for ( i = 1; i <= num_maps[map_type]; ++i ) { const char* mapname = ex_name_of_map( map_enums[map_type], i ); if (nc_inq_varid(exoid, mapname, &temp) != NC_NOERR) { if ((status = nc_def_var(exoid, mapname, NC_INT, 1, dims, &temp)) != NC_NOERR) { exerrval = status; if ( status == NC_ENAMEINUSE ) { sprintf( errmsg, "Error: number map %s already exists in file id %d", mapname, exoid ); } else { sprintf( errmsg, "Error: failed to create number map array %s in file id %d", mapname, exoid ); } ex_err( "ex_put_concat_all_blocks", errmsg, exerrval ); goto error_ret; /* exit define mode and return */ } } } } } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete element block definition in file id %d", exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_concat_all_blocks",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgevt.c0000755000175000017500000000631211606020250022261 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgevt - ex_get_elem_var_time * * entry conditions - * input parameters: * int exoid exodus file id * int elem_var_index element variable index * int elem_number element number * int beg_time_step time step number * int end_time_step time step number * * exit conditions - * float* elem_var_vals array of element variable values * * revision history - * 20061002 - David Thompson - Moved to ex_get_var_time. * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the values of an element variable for a single element through a * specified number of time steps in the database; assume the first element * variable index, element number, and time step are 1 * \deprecated Use ex_get_var_time()(exoid, EX_ELEM_BLOCK, elem_var_index, elem_number, beg_time_step, end_time_step, elem_var_vals) */ int ex_get_elem_var_time (int exoid, int elem_var_index, int elem_number, int beg_time_step, int end_time_step, void *elem_var_vals) { return ex_get_var_time( exoid, EX_ELEM_BLOCK, elem_var_index, elem_number, beg_time_step, end_time_step, elem_var_vals ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnsi.c0000755000175000017500000000472511606020250022262 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnsi - ex_get_node_set_ids * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int node_set_ids array of node set ids * * revision history - * * $Id: exgnsi.c,v 1.1 2010-01-06 16:33:14 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the node set ids from the database * \deprecated Use ex_get_ids()(exoid, EX_NODE_SET, ids) */ int ex_get_node_set_ids (int exoid, int *ids) { return ex_get_ids( exoid, EX_NODE_SET, ids ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expsetp.c0000644000175000017500000003254511606020250022453 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expsetp - ex_put_set_param * * entry conditions - * input parameters: * int exoid exodus file id * int set_type the type of set * int set_id set id * int num_entries_in_set number of entries in the set * int num_dist_fact_in_set number of distribution factors in the * set * * exit conditions - * * revision history - * * $Id: expsetp.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the set id and the number of entries which describe a single set * \param exoid exodus file id * \param set_type the type of set * \param set_id set id * \param num_entries_in_set number of entries in the set * \param num_dist_fact_in_set number of distribution factors in the set */ int ex_put_set_param (int exoid, ex_entity_type set_type, int set_id, int num_entries_in_set, int num_dist_fact_in_set) { int status; size_t temp; int dimid, varid, set_id_ndx, dims[1]; size_t start[1]; int num_sets; int ldum; int cur_num_sets, set_stat; char *cdum; char errmsg[MAX_ERR_LENGTH]; char* dimptr; char* idsptr; char* statptr; char* numentryptr = NULL; char* numdfptr = NULL; char* factptr = NULL; char* entryptr = NULL; char* extraptr = NULL; exerrval = 0; /* clear error code */ cdum = 0; /* setup pointers based on set_type NOTE: there is another block that sets more stuff later ... */ if (set_type == EX_NODE_SET) { dimptr = DIM_NUM_NS; idsptr = VAR_NS_IDS; statptr = VAR_NS_STAT; } else if (set_type == EX_EDGE_SET) { dimptr = DIM_NUM_ES; idsptr = VAR_ES_IDS; statptr = VAR_ES_STAT; } else if (set_type == EX_FACE_SET) { dimptr = DIM_NUM_FS; idsptr = VAR_FS_IDS; statptr = VAR_FS_STAT; } else if (set_type == EX_SIDE_SET) { dimptr = DIM_NUM_SS; idsptr = VAR_SS_IDS; statptr = VAR_SS_STAT; } else if (set_type == EX_ELEM_SET) { dimptr = DIM_NUM_ELS; idsptr = VAR_ELS_IDS; statptr = VAR_ELS_STAT; } else { exerrval = EX_FATAL; sprintf(errmsg, "Error: invalid set type (%d)", set_type); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } /* first check if any of that set type is specified */ if ((status = nc_inq_dimid(exoid, dimptr, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: no %ss specified in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } /* Check for duplicate set id entry */ ex_id_lkup(exoid, set_type, set_id); if (exerrval != EX_LOOKUPFAIL) { /* found the side set id */ sprintf(errmsg, "Error: %s %d already defined in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); return(EX_FATAL); } /* Get number of sets specified for this file */ if ((status = nc_inq_dimlen(exoid,dimid,&temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of %ss in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } num_sets = temp; /* Keep track of the total number of sets defined using a counter stored in a linked list keyed by exoid. NOTE: ex_get_file_item finds the maximum number of sets defined for a specific file and returns that value. */ cur_num_sets=ex_get_file_item(exoid, ex_get_counter_list(set_type)); if (cur_num_sets >= num_sets) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of %ss (%d) defined in file id %d", ex_name_of_object(set_type), num_sets,exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } /* NOTE: ex_inc_file_item finds the current number of sets defined for a specific file and returns that value incremented. */ cur_num_sets=ex_inc_file_item(exoid, ex_get_counter_list(set_type)); set_id_ndx = cur_num_sets + 1; /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { numentryptr = DIM_NUM_NOD_NS(set_id_ndx); entryptr = VAR_NODE_NS(set_id_ndx); extraptr = NULL; /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */ numdfptr = DIM_NUM_NOD_NS(set_id_ndx); factptr = VAR_FACT_NS(set_id_ndx); } else if (set_type == EX_EDGE_SET) { numentryptr = DIM_NUM_EDGE_ES(set_id_ndx); entryptr = VAR_EDGE_ES(set_id_ndx); extraptr = VAR_ORNT_ES(set_id_ndx); numdfptr = DIM_NUM_DF_ES(set_id_ndx); factptr = VAR_FACT_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { numentryptr = DIM_NUM_FACE_FS(set_id_ndx); entryptr = VAR_FACE_FS(set_id_ndx); extraptr = VAR_ORNT_FS(set_id_ndx); numdfptr = DIM_NUM_DF_FS(set_id_ndx); factptr = VAR_FACT_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { numentryptr = DIM_NUM_SIDE_SS(set_id_ndx); entryptr = VAR_ELEM_SS(set_id_ndx); extraptr = VAR_SIDE_SS(set_id_ndx); numdfptr = DIM_NUM_DF_SS(set_id_ndx); factptr = VAR_FACT_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { numentryptr = DIM_NUM_ELE_ELS(set_id_ndx); entryptr = VAR_ELEM_ELS(set_id_ndx); extraptr = NULL; numdfptr = DIM_NUM_DF_ELS(set_id_ndx); factptr = VAR_FACT_ELS(set_id_ndx); } /* write out information to previously defined variable */ /* first: get id of set id variable */ if ((status = nc_inq_varid(exoid, idsptr, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s %d in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } /* write out set id */ start[0] = cur_num_sets; ldum = (int)set_id; if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s id %d in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } if (num_entries_in_set == 0) /* Is this a NULL set? */ set_stat = 0; /* change set status to NULL */ else set_stat = 1; /* change set status to TRUE */ if ((status = nc_inq_varid(exoid, statptr, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s status in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } ldum = (int)set_stat; if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s %d status to file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } if (num_entries_in_set == 0) {/* Is this a NULL set? */ return(EX_NOERR); } /* put netcdf file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } /* define dimensions and variables */ if ((status = nc_def_dim(exoid, numentryptr, num_entries_in_set, &dimid)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { sprintf(errmsg, "Error: %s %d size already defined in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); } else { sprintf(errmsg, "Error: failed to define number of entries in %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); } goto error_ret; } /* create variable array in which to store the entry lists */ dims[0] = dimid; if ((status = nc_def_var(exoid, entryptr, NC_INT, 1, dims, &varid)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { sprintf(errmsg, "Error: entry list already exists for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); } else { sprintf(errmsg, "Error: failed to create entry list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } if (extraptr) { if ((status = nc_def_var(exoid, extraptr, NC_INT, 1, dims, &varid)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { sprintf(errmsg, "Error: extra list already exists for %s %d in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_put_set_param",errmsg,exerrval); } else { sprintf(errmsg, "Error: failed to create extra list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } } /* Create distribution factors variable if required */ if (num_dist_fact_in_set > 0) { if (set_type == EX_NODE_SET) { /* but num_dist_fact_in_set must equal number of nodes */ if (num_dist_fact_in_set != num_entries_in_set) { exerrval = EX_FATAL; sprintf(errmsg, "Error: # dist fact (%d) not equal to # nodes (%d) in node set %d file id %d", num_dist_fact_in_set, num_entries_in_set, set_id, exoid); ex_err("ex_put_set_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* resuse dimid from entry lists */ } else { if ((status = nc_def_dim(exoid, numdfptr, num_dist_fact_in_set, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of dist factors in %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* create variable array in which to store the set distribution factors */ dims[0] = dimid; if ((status = nc_def_var(exoid, factptr, nc_flt_code(exoid), 1, dims, &varid)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { sprintf(errmsg, "Error: dist factors list already exists for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); } else { sprintf(errmsg, "Error: failed to create dist factors list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set_param",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete definition in file id %d", exoid); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_set_param",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expini.c0000755000175000017500000000757611606020250022270 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expini - ex_put_init * * entry conditions - * input parameters: * int exoid exodus file id * char* title title of file * int num_dim number of dimensions (per node) * int num_nodes number of nodes * int num_elem number of elements * int num_elem_blk number of element blocks * int num_node_sets number of node sets * int num_side_sets number of side sets * * exit conditions - * * $Id: expini.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the initialization parameters to the EXODUS II file * \param exoid exodus file id * \param title title of file * \param num_dim number of dimensions (per node) * \param num_nodes number of nodes * \param num_elem number of elements * \param num_elem_blk number of element blocks * \param num_node_sets number of node sets * \param num_side_sets number of side sets */ int ex_put_init (int exoid, const char *title, int num_dim, int num_nodes, int num_elem, int num_elem_blk, int num_node_sets, int num_side_sets) { ex_init_params par; strcpy( par.title, title ); par.num_dim = num_dim; par.num_nodes = num_nodes; par.num_edge = 0; par.num_edge_blk = 0; par.num_face = 0; par.num_face_blk = 0; par.num_elem = num_elem; par.num_elem_blk = num_elem_blk; par.num_node_sets = num_node_sets; par.num_edge_sets = 0; par.num_face_sets = 0; par.num_side_sets = num_side_sets; par.num_elem_sets = 0; par.num_node_maps = 0; par.num_edge_maps = 0; par.num_face_maps = 0; par.num_elem_maps = 0; return (ex_put_init_ext( exoid, &par )); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgblk.c0000644000175000017500000002374611606020250022242 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgblk - read block parameters * * entry conditions - * input parameters: * int idexo exodus file id * int blk_type block type (edge,face,element) * int blk_id block id * * exit conditions - * char* elem_type element type name * int* num_entries_this_blk number of elements in this element block * int* num_nodes_per_entry number of nodes per element block * int* num_attr_per_entry number of attributes * * revision history - * * $Id: exgblk.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * */ #include #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the parameters used to describe an edge, face, or element block */ int ex_get_block( int exoid, ex_entity_type blk_type, int blk_id, char* elem_type, int* num_entries_this_blk, int* num_nodes_per_entry, int* num_edges_per_entry, int* num_faces_per_entry, int* num_attr_per_entry ) { int dimid, connid, blk_id_ndx; size_t len; char *ptr; char errmsg[MAX_ERR_LENGTH]; int status; const char* dnument; const char* dnumnod; const char* dnumedg; const char* dnumfac; const char* dnumatt; const char* ablknam; const char* vblkcon; exerrval = 0; /* First, locate index of element block id in VAR_ID_EL_BLK array */ blk_id_ndx = ex_id_lkup(exoid,blk_type,blk_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { /* NULL element block? */ if ( elem_type ) strcpy(elem_type, "NULL"); /* NULL element type name */ *num_entries_this_blk = 0; /* no elements */ *num_nodes_per_entry = 0; /* no nodes */ *num_attr_per_entry = 0; /* no attributes */ return (EX_NOERR); } else { sprintf(errmsg, "Error: failed to locate %s id %d in id array in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_get_block",errmsg,exerrval); return (EX_FATAL); } } switch (blk_type) { case EX_EDGE_BLOCK: dnument = DIM_NUM_ED_IN_EBLK(blk_id_ndx); dnumnod = DIM_NUM_NOD_PER_ED(blk_id_ndx); dnumedg = 0; dnumfac = 0; dnumatt = DIM_NUM_ATT_IN_EBLK(blk_id_ndx); vblkcon = VAR_EBCONN(blk_id_ndx); ablknam = ATT_NAME_ELB; break; case EX_FACE_BLOCK: dnument = DIM_NUM_FA_IN_FBLK(blk_id_ndx); dnumnod = DIM_NUM_NOD_PER_FA(blk_id_ndx); dnumedg = 0; /* it is possible this might be non-NULL some day */ dnumfac = 0; dnumatt = DIM_NUM_ATT_IN_FBLK(blk_id_ndx); vblkcon = VAR_FBCONN(blk_id_ndx); ablknam = ATT_NAME_ELB; break; case EX_ELEM_BLOCK: dnument = DIM_NUM_EL_IN_BLK(blk_id_ndx); dnumnod = DIM_NUM_NOD_PER_EL(blk_id_ndx); dnumedg = DIM_NUM_EDG_PER_EL(blk_id_ndx); dnumfac = DIM_NUM_FAC_PER_EL(blk_id_ndx); dnumatt = DIM_NUM_ATT_IN_BLK(blk_id_ndx); vblkcon = VAR_CONN(blk_id_ndx); ablknam = ATT_NAME_ELB; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Bad block type parameter (%d) specified for file id %d.", blk_type, exoid ); return (EX_FATAL); } /* inquire values of some dimensions */ if ( num_entries_this_blk ) { if ((status = nc_inq_dimid (exoid, dnument, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of entities in %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } if ((status = nc_inq_dimlen (exoid, dimid, &len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of %ss in block %d in file id %d", ex_name_of_object(blk_type),blk_id, exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } *num_entries_this_blk = len; } if ( num_nodes_per_entry ) { if ((status = nc_inq_dimid (exoid, dnumnod, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of nodes/entity in %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } if ((status = nc_inq_dimlen (exoid, dimid, &len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of nodes/entity in %s %d in file id %d", ex_name_of_object(blk_type),blk_id, exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } *num_nodes_per_entry = len; } if ( num_edges_per_entry ) { if ( blk_type != EX_ELEM_BLOCK ) { exerrval = (EX_WARN); sprintf(errmsg, "Warning: non-NULL pointer passed to num_edges_per_entry for %s query in file id %d", ex_name_of_object(blk_type),exoid); ex_err("ex_get_block",errmsg,exerrval); } else { if ((status = nc_inq_dimid (exoid, dnumedg, &dimid)) != NC_NOERR) { /* undefined => no edge entries per element */ *num_edges_per_entry = 0; } else { if ((status = nc_inq_dimlen (exoid, dimid, &len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of edges/entry in %s %d in file id %d", ex_name_of_object(blk_type),blk_id, exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } *num_edges_per_entry = len; } } } if ( num_faces_per_entry ) { if ( blk_type != EX_ELEM_BLOCK ) { exerrval = (EX_WARN); sprintf(errmsg, "Warning: non-NULL pointer passed to num_faces_per_entry for %s query in file id %d", ex_name_of_object(blk_type),exoid); ex_err("ex_get_block",errmsg,exerrval); } else { if ((status = nc_inq_dimid (exoid, dnumfac, &dimid)) != NC_NOERR) { /* undefined => no face entries per element */ *num_faces_per_entry = 0; } else { if ((status = nc_inq_dimlen(exoid, dimid, &len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of faces/entity in %s %d in file id %d", ex_name_of_object(blk_type),blk_id, exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } *num_faces_per_entry = len; } } } if ( num_attr_per_entry ) { if ((status = nc_inq_dimid (exoid, dnumatt, &dimid)) != NC_NOERR) { /* dimension is undefined */ *num_attr_per_entry = 0; } else { if ((status = nc_inq_dimlen(exoid, dimid, &len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of attributes in %s %d in file id %d", ex_name_of_object(blk_type),blk_id, exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } *num_attr_per_entry = len; } } if ( elem_type ) { /* look up connectivity array for this element block id */ if ((status = nc_inq_varid (exoid, vblkcon, &connid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate connectivity array for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } if ((status = nc_inq_attlen (exoid, connid, ablknam, &len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s %d type in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } if (len > (MAX_STR_LENGTH+1)) { len = MAX_STR_LENGTH; sprintf (errmsg, "Warning: %s %d type will be truncated to %ld chars", ex_name_of_object(blk_type), blk_id, (long)(len)); ex_err("ex_get_block",errmsg,EX_MSG); } /* get the element type name */ if ((status = nc_get_att_text (exoid, connid, ablknam, elem_type)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to get %s %d type in file id %d", ex_name_of_object(blk_type), blk_id, exoid); ex_err("ex_get_block",errmsg, exerrval); return(EX_FATAL); } /* get rid of trailing blanks */ ptr = elem_type; /* fprintf(stderr,"[exgblk] %s, len: %d\n",ptr,len); */ while (ptr < elem_type + len && *ptr != ' ') { ptr++; } *(ptr) = '\0'; } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expatt.c0000644000175000017500000001237411606020250022266 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expatt - ex_put_attr * * entry conditions - * input parameters: * int exoid exodus file id * int blk_type block type * int blk_id block id * float* attrib array of attributes * * exit conditions - * * revision history - * * $Id: expatt.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the attributes for an edge/face/element block * \param exoid exodus file id * \param blk_type block type * \param blk_id block id * \param attrib array of attributes */ int ex_put_attr (int exoid, ex_entity_type blk_type, int blk_id, const void *attrib) { int status; int attrid, blk_id_ndx = 0; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ if ( blk_type != EX_NODAL ) { /* Determine index of blk_id in VAR_ID_EL_BLK array */ blk_id_ndx = ex_id_lkup(exoid,blk_type,blk_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes allowed for NULL %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_attr",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this block */ } else { sprintf(errmsg, "Error: no %s id %d in in file id %d", ex_name_of_object(blk_type), blk_id, exoid); ex_err("ex_put_attr",errmsg,exerrval); return (EX_FATAL); } } } switch (blk_type) { case EX_SIDE_SET: status = nc_inq_varid (exoid, VAR_SSATTRIB(blk_id_ndx), &attrid); break; case EX_NODE_SET: status = nc_inq_varid (exoid, VAR_NSATTRIB(blk_id_ndx), &attrid); break; case EX_EDGE_SET: status = nc_inq_varid (exoid, VAR_ESATTRIB(blk_id_ndx), &attrid); break; case EX_FACE_SET: status = nc_inq_varid (exoid, VAR_FSATTRIB(blk_id_ndx), &attrid); break; case EX_ELEM_SET: status = nc_inq_varid (exoid, VAR_ELSATTRIB(blk_id_ndx), &attrid); break; case EX_NODAL: status = nc_inq_varid (exoid, VAR_NATTRIB, &attrid); break; case EX_EDGE_BLOCK: status = nc_inq_varid (exoid, VAR_EATTRIB(blk_id_ndx), &attrid); break; case EX_FACE_BLOCK: status = nc_inq_varid (exoid, VAR_FATTRIB(blk_id_ndx), &attrid); break; case EX_ELEM_BLOCK: status = nc_inq_varid (exoid, VAR_ATTRIB(blk_id_ndx), &attrid); break; default: sprintf(errmsg, "Error: Called with invalid blk_type %d", blk_type ); ex_err("ex_put_attr",errmsg,exerrval); return (EX_FATAL); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate attribute variable for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_attr",errmsg,exerrval); return (EX_FATAL); } /* write out the attributes */ if (ex_comp_ws(exoid) == 4) { status = nc_put_var_float(exoid, attrid, attrib); } else { status = nc_put_var_double(exoid, attrid, attrib); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put attributes for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_attr",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expblk.c0000644000175000017500000003732311606020250022247 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expblk - ex_put_block: write edge, face, or element block parameters * * entry conditions - * input parameters: * int idexo exodus file id * int blk_type type of block (edge, face, or element) * int blk_id block identifer * char* entry_descrip string describing shape of entries in the block * int num_entries_this_blk number of entries(records) in the block * int num_nodes_per_entry number of nodes per block entry * int num_edges_per_entry number of edges per block entry * int num_faces_per_entry number of faces per block entry * int num_attr_per_entry number of attributes per block entry * * exit conditions - * * $Id: expblk.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the parameters used to describe an element block * \param exoid exodus file id * \param blk_type type of block (edge, face, or element) * \param blk_id block identifer * \param entry_descrip string describing shape of entries in the block * \param num_entries_this_blk number of entries(records) in the block * \param num_nodes_per_entry number of nodes per block entry * \param num_edges_per_entry number of edges per block entry * \param num_faces_per_entry number of faces per block entry * \param num_attr_per_entry number of attributes per block entry */ int ex_put_block( int exoid, ex_entity_type blk_type, int blk_id, const char* entry_descrip, int num_entries_this_blk, int num_nodes_per_entry, int num_edges_per_entry, int num_faces_per_entry, int num_attr_per_entry ) { int status; int varid, dimid, dims[2], blk_id_ndx, blk_stat, strdim; size_t start[2]; int num_blk; size_t temp; int cur_num_blk, numblkdim, numattrdim; int nnodperentdim, nedgperentdim, nfacperentdim; int connid; char *cdum; char errmsg[MAX_ERR_LENGTH]; const char* dnumblk; const char* vblkids; const char* vblksta; const char* vnodcon; const char* vedgcon; const char* vfaccon; const char* vattnam; const char* vblkatt; const char* dneblk; const char* dnape; const char* dnnpe; const char* dnepe; const char* dnfpe; exerrval = 0; /* clear error code */ cdum = 0; switch (blk_type) { case EX_EDGE_BLOCK: dnumblk = DIM_NUM_ED_BLK; vblkids = VAR_ID_ED_BLK; vblksta = VAR_STAT_ED_BLK; break; case EX_FACE_BLOCK: dnumblk = DIM_NUM_FA_BLK; vblkids = VAR_ID_FA_BLK; vblksta = VAR_STAT_FA_BLK; break; case EX_ELEM_BLOCK: dnumblk = DIM_NUM_EL_BLK; vblkids = VAR_ID_EL_BLK; vblksta = VAR_STAT_EL_BLK; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Bad block type (%d) specified for file id %d", blk_type, exoid ); ex_err( "ex_put_block", errmsg, exerrval ); return (EX_FATAL); } /* first check if any element blocks are specified */ if ((status = ex_get_dimension(exoid, dnumblk, ex_name_of_object(blk_type), &temp, &dimid, "ex_put_block")) != NC_NOERR) { return EX_FATAL; } num_blk = temp; /* Next: Make sure that this is not a duplicate element block id by searching the vblkids array. WARNING: This must be done outside of define mode because id_lkup accesses the database to determine the position */ if ((status = nc_inq_varid(exoid, vblkids, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s ids in file id %d", ex_name_of_object(blk_type), exoid); ex_err("ex_put_block",errmsg,exerrval); } blk_id_ndx = ex_id_lkup(exoid,blk_type,blk_id); if (exerrval != EX_LOOKUPFAIL) { /* found the element block id */ exerrval = EX_FATAL; sprintf(errmsg, "Error: %s id %d already exists in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } /* Keep track of the total number of element blocks defined using a counter stored in a linked list keyed by exoid. NOTE: ex_get_file_item is a function that finds the number of element blocks for a specific file and returns that value incremented. */ cur_num_blk=ex_get_file_item(exoid, ex_get_counter_list(blk_type)); if (cur_num_blk >= num_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of %ss (%d) defined in file id %d", ex_name_of_object(blk_type), num_blk,exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } /* NOTE: ex_get_file_item is a function that finds the number of element blocks for a specific file and returns that value incremented. */ cur_num_blk=ex_inc_file_item(exoid, ex_get_counter_list(blk_type)); start[0] = cur_num_blk; /* write out element block id to previously defined id array variable*/ if ((status = nc_put_var1_int(exoid, varid, start, &blk_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s id to file id %d", ex_name_of_object(blk_type), exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } blk_id_ndx = start[0]+1; /* element id index into vblkids array*/ if (num_entries_this_blk == 0) /* Is this a NULL element block? */ blk_stat = 0; /* change element block status to NULL */ else blk_stat = 1; /* change element block status to TRUE */ if ((status = nc_inq_varid (exoid, vblksta, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s status in file id %d", ex_name_of_object(blk_type), exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_put_var1_int(exoid, varid, start, &blk_stat)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s id %d status to file id %d", ex_name_of_object(blk_type), blk_id, exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } if (num_entries_this_blk == 0) {/* Is this a NULL element block? */ return(EX_NOERR); } /* put netcdf file into define mode */ if ((status=nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } switch (blk_type) { case EX_EDGE_BLOCK: dneblk = DIM_NUM_ED_IN_EBLK(blk_id_ndx); dnnpe = DIM_NUM_NOD_PER_ED(blk_id_ndx); dnepe = 0; dnfpe = 0; dnape = DIM_NUM_ATT_IN_EBLK(blk_id_ndx); vblkatt = VAR_EATTRIB(blk_id_ndx); vattnam = VAR_NAME_EATTRIB(blk_id_ndx); vnodcon = VAR_EBCONN(blk_id_ndx); vedgcon = 0; vfaccon = 0; break; case EX_FACE_BLOCK: dneblk = DIM_NUM_FA_IN_FBLK(blk_id_ndx); dnnpe = DIM_NUM_NOD_PER_FA(blk_id_ndx); dnepe = 0; dnfpe = 0; dnape = DIM_NUM_ATT_IN_FBLK(blk_id_ndx); vblkatt = VAR_FATTRIB(blk_id_ndx); vattnam = VAR_NAME_FATTRIB(blk_id_ndx); vnodcon = VAR_FBCONN(blk_id_ndx); vedgcon = 0; vfaccon = 0; break; case EX_ELEM_BLOCK: dneblk = DIM_NUM_EL_IN_BLK(blk_id_ndx); dnnpe = DIM_NUM_NOD_PER_EL(blk_id_ndx); dnepe = DIM_NUM_EDG_PER_EL(blk_id_ndx); dnfpe = DIM_NUM_FAC_PER_EL(blk_id_ndx); dnape = DIM_NUM_ATT_IN_BLK(blk_id_ndx); vblkatt = VAR_ATTRIB(blk_id_ndx); vattnam = VAR_NAME_ATTRIB(blk_id_ndx); vnodcon = VAR_CONN(blk_id_ndx); vedgcon = VAR_ECONN(blk_id_ndx); vfaccon = VAR_FCONN(blk_id_ndx); break; default: sprintf(errmsg, "Error: Called with invalid blk_type %d", blk_type ); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } /* define some dimensions and variables*/ if ((status = nc_def_dim(exoid,dneblk,num_entries_this_blk, &numblkdim )) != NC_NOERR) { if (status == NC_ENAMEINUSE) { /* duplicate entry */ exerrval = status; sprintf(errmsg, "Error: %s %d already defined in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define number of entities/block for %s %d file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } if ((status = nc_def_dim(exoid,dnnpe,num_nodes_per_entry, &nnodperentdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of nodes/entity for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if (dnepe && num_edges_per_entry > 0 ) { if ((status = nc_def_dim (exoid,dnepe,num_edges_per_entry, &nedgperentdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of edges/entity for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if ( dnfpe && num_faces_per_entry > 0 ) { if ((status = nc_def_dim(exoid,dnfpe,num_faces_per_entry, &nfacperentdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of faces/entity for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* element attribute array */ if (num_attr_per_entry > 0) { if ((status = nc_def_dim(exoid, dnape, num_attr_per_entry, &numattrdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of attributes in %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } dims[0] = numblkdim; dims[1] = numattrdim; if ((status = nc_def_var(exoid, vblkatt, nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define attributes for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_STR, &strdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } /* Attribute names... */ dims[0] = numattrdim; dims[1] = strdim; if ((status = nc_def_var(exoid, vattnam, NC_CHAR, 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define %s attribute name array in file id %d", ex_name_of_object(blk_type), exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* element connectivity array */ dims[0] = numblkdim; dims[1] = nnodperentdim; if ((status = nc_def_var(exoid, vnodcon, NC_INT, 2, dims, &connid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create connectivity array for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store element type as attribute of connectivity variable */ if ((status = nc_put_att_text(exoid, connid, ATT_NAME_ELB, strlen(entry_descrip)+1, entry_descrip)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s type name %s in file id %d", ex_name_of_object(blk_type), entry_descrip,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if (vedgcon && num_edges_per_entry ) { dims[0] = numblkdim; dims[1] = nedgperentdim; if ((status = nc_def_var(exoid, vedgcon, NC_INT, 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create edge connectivity array for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if ( vfaccon && num_faces_per_entry ) { dims[0] = numblkdim; dims[1] = nfacperentdim; if ((status = nc_def_var(exoid, vfaccon, NC_INT, 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create face connectivity array for %s %d in file id %d", ex_name_of_object(blk_type), blk_id,exoid); ex_err("ex_put_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* leave define mode */ if ((exerrval=nc_enddef (exoid)) != NC_NOERR) { sprintf(errmsg, "Error: failed to complete %s definition in file id %d", ex_name_of_object(blk_type), exoid); ex_err("ex_put_block",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_block",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgssd.c0000755000175000017500000000526611606020250022263 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgssd - ex_get_side_set_dist_fact * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * * exit conditions - * float* side_set_dist_fact array of dist factors for side set * * revision history - * * $Id: exgssd.c,v 1.1 2010-01-06 16:33:37 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the distribution factors for a single side set * \deprecated Use ex_get_set_dist_fact()(exoid, EX_SIDE_SET, side_set_id, side_set_dist_fact) */ int ex_get_side_set_dist_fact (int exoid, int side_set_id, void *side_set_dist_fact) { return ex_get_set_dist_fact(exoid, EX_SIDE_SET, side_set_id, side_set_dist_fact); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expgv.c0000755000175000017500000000607211606020250022113 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expgv - ex_put_glo_vars * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int num_glob_vars number of global vars in file * float* glob_var_vals array of global variable values * * exit conditions - * * revision history - * * $Id: expgv.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of all the global variables for a single time step to * the database; time step numbers are assumed to start at 1 * \param exoid exodus file id * \param time_step time step number * \param num_glob_vars number of global vars in file * \param glob_var_vals array of global variable values * \deprecated Use ex_put_var()(exoid, time_step, EX_GLOBAL, 1, 0, num_glob_vars, glob_var_vals) */ int ex_put_glob_vars (int exoid, int time_step, int num_glob_vars, const void *glob_var_vals) { return ex_put_var( exoid, time_step, EX_GLOBAL, 1, 0 /*N/A*/, num_glob_vars, glob_var_vals ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnsv.c0000644000175000017500000000666711606020250022314 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expmv - ex_put_nset_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int nset_var_index nodeset variable index * int nset_id nodeset id * int num_nodes_this_nset number of nodes in this nodeset * * exit conditions - * * * exit conditions - * * revision history - * * $Id: expnsv.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of a single nodeset variable for one nodeset at * one time step to the database; assume the first time step and * nodeset variable index are 1 * \param exoid exodus file id * \param time_step time step number * \param nset_var_index nodeset variable index * \param nset_id nodeset id * \param num_nodes_this_nset number of nodes in this nodeset * \param nset_var_vals the values to be written * \deprecated Use ex_put_var()(exoid, time_step, EX_NODE_SET, nset_var_index, nset_id, num_nodes_this_nset, nset_var_vals) */ int ex_put_nset_var (int exoid, int time_step, int nset_var_index, int nset_id, int num_nodes_this_nset, const void *nset_var_vals) { return ex_put_var(exoid, time_step, EX_NODE_SET, nset_var_index, nset_id, num_nodes_this_nset, nset_var_vals); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgssc.c0000755000175000017500000005520411606020250022257 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgssc - ex_get_side_set_node_count * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * * exit conditions - * int *side_set_node_cnt_list returned array of number of nodes for * side or face * revision history - * * $Id: exgssc.c,v 1.1 2010-01-06 16:33:36 kwleiter Exp $ *****************************************************************************/ #include #include #include #include #include "exodusII.h" #include "exodusII_int.h" /* Generic error message for element type/node count mapping...*/ #define EL_NODE_COUNT_ERROR sprintf(errmsg, \ "Error: An element of type '%s' with %d nodes is not valid.",\ elem_blk_parms[i].elem_type,\ elem_blk_parms[i].num_nodes_per_elem);\ ex_err("ex_get_side_set_node_count",errmsg,EX_MSG);\ return(EX_FATAL);\ int ex_get_side_set_node_count(int exoid, int side_set_id, int *side_set_node_cnt_list) { int ii, i, j, m; int num_side_sets, num_elem_blks, num_df, ndim; int tot_num_elem = 0, tot_num_ss_elem = 0, side, elem; int *elem_blk_ids; int *ss_elem_ndx; int *side_set_elem_list, *side_set_side_list; int elem_ctr; int num_elem_in_blk, num_nodes_per_elem, num_attr; float fdum; char *cdum, elem_type[MAX_STR_LENGTH+1]; struct elem_blk_parm *elem_blk_parms; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ cdum = 0; /* initialize even though it is not used */ /* first check if any side sets are specified */ /* inquire how many side sets have been stored */ if ((ex_inquire(exoid, EX_INQ_SIDE_SETS, &num_side_sets, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of side sets in file id %d",exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return(EX_FATAL); } if (num_side_sets == 0) { sprintf(errmsg, "Warning: no side sets defined in file id %d",exoid); ex_err("ex_get_side_set_node_count",errmsg,EX_WARN); return(EX_WARN); } /* Lookup index of side set id in VAR_SS_IDS array */ ex_id_lkup(exoid,EX_SIDE_SET,side_set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: side set %d is NULL in file id %d", side_set_id,exoid); ex_err("ex_get_side_set_node_count",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate side set id %d in VAR_SS_IDS array in file id %d", side_set_id,exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return (EX_FATAL); } } if ((ex_inquire(exoid, EX_INQ_ELEM_BLK, &num_elem_blks, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of element blocks in file id %d",exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return(EX_FATAL); } if ((ex_inquire(exoid, EX_INQ_ELEM, &tot_num_elem, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get total number of elements in file id %d",exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return(EX_FATAL); } /* get the dimensionality of the coordinates; this is necessary to distinguish between 2d TRIs and 3d TRIs */ if ((ex_inquire(exoid, EX_INQ_DIM, &ndim, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get dimensionality in file id %d",exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); return(EX_FATAL); } /* First determine the # of elements in the side set*/ if ((ex_get_side_set_param(exoid,side_set_id,&tot_num_ss_elem,&num_df)) == -1) { sprintf(errmsg, "Error: failed to get number of elements in side set %d in file id %d", side_set_id, exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return(EX_FATAL); } /* Allocate space for the side set element list */ if (!(side_set_elem_list=malloc(tot_num_ss_elem*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set element list for file id %d", exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return (EX_FATAL); } /* Allocate space for the side set side list */ if (!(side_set_side_list=malloc(tot_num_ss_elem*sizeof(int)))) { free(side_set_elem_list); exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set side list for file id %d", exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return (EX_FATAL); } if (ex_get_side_set(exoid, side_set_id, side_set_elem_list, side_set_side_list) == -1) { free(side_set_elem_list); free(side_set_side_list); sprintf(errmsg, "Error: failed to get side set %d in file id %d", side_set_id, exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return (EX_FATAL); } /* Allocate space for the ss element index array */ if (!(ss_elem_ndx=malloc(tot_num_ss_elem*sizeof(int)))) { free(side_set_elem_list); free(side_set_side_list); exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set elem sort array for file id %d", exoid); ex_err("ex_get_side_set_node_count",errmsg,exerrval); return (EX_FATAL); } /* Sort side set element list into index array - non-destructive */ for (i=0;i 1) { if ((status = nc_inq_varid(exoid, VAR_COORD_Y, &coordidy)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate y nodal coordinates in file id %d", exoid); ex_err("ex_put_coord",errmsg,exerrval); return (EX_FATAL); } } else { coordidy = 0; } if (num_dim > 2) { if ((status = nc_inq_varid(exoid, VAR_COORD_Z, &coordidz)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate z nodal coordinates in file id %d", exoid); ex_err("ex_put_coord",errmsg,exerrval); return (EX_FATAL); } } else { coordidz = 0; } /* write out the coordinates */ for (i=0; i #include "exodusII.h" #include "exodusII_int.h" /*! * reads the element block ids from the database * \deprecated Use ex_get_ids()(exoid, EX_ELEM_BLOCK, ids) instead */ int ex_get_elem_blk_ids (int exoid, int *ids) { /* ex_get_elem_blk_ids should be deprecated. */ return ex_get_ids( exoid, EX_ELEM_BLOCK, ids ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expean.c0000644000175000017500000000536611606020250022244 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expeat - ex_put_elem_attr_names * * entry conditions - * input parameters: * int exoid exodus file id * int elem_blk_id element block id * char* names[] ptr array of attribute names * * exit conditions - * * revision history - * * $Id: expean.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the attribute names for an element block * \param exoid exodus file id * \param elem_blk_id element block id * \param names[] ptr array of attribute names * \deprecated Use ex_put_attr_names()(exoid, EX_ELEM_BLOCK, elem_blk_id, names) */ int ex_put_elem_attr_names(int exoid, int elem_blk_id, char* names[]) { return ex_put_attr_names( exoid, EX_ELEM_BLOCK, elem_blk_id, names ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgsetp.c0000644000175000017500000001506111606020250022434 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgsetp - ex_get_set_param * * entry conditions - * input parameters: * int exoid exodus file id * int set_type the type of set * int set_id set id * * exit conditions - * int* num_entries_in_set number of entries in the set * int* num_dist_fact_in_set number of distribution factors in the * set * * revision history - * * $Id: exgsetp.c,v 1.1 2010-01-06 16:33:36 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the number of entries and the number of distribution factors which * describe a single set */ int ex_get_set_param (int exoid, ex_entity_type set_type, int set_id, int *num_entry_in_set, int *num_dist_fact_in_set) { int status; int varid, dimid, set_id_ndx; size_t lnum_entry_in_set; size_t lnum_dist_fact_in_set; char errmsg[MAX_ERR_LENGTH]; char* numentryptr = NULL; char* numdfptr = NULL; exerrval = 0; /* clear error code */ /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no %ss stored in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_get_set_param",errmsg,exerrval); return (EX_WARN); } /* Lookup index of set id in VAR_*S_IDS array */ set_id_ndx = ex_id_lkup(exoid,set_type,set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) /* NULL set? */ { *num_entry_in_set = 0; *num_dist_fact_in_set = 0; return (EX_NOERR); } else { sprintf(errmsg, "Error: failed to locate %s id %d in id array in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set_param",errmsg,exerrval); return (EX_FATAL); } } /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { numentryptr = DIM_NUM_NOD_NS(set_id_ndx); /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */ numdfptr = DIM_NUM_NOD_NS(set_id_ndx); } else if (set_type == EX_EDGE_SET) { numentryptr = DIM_NUM_EDGE_ES(set_id_ndx); numdfptr = DIM_NUM_DF_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { numentryptr = DIM_NUM_FACE_FS(set_id_ndx); numdfptr = DIM_NUM_DF_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { numentryptr = DIM_NUM_SIDE_SS(set_id_ndx); numdfptr = DIM_NUM_DF_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { numentryptr = DIM_NUM_ELE_ELS(set_id_ndx); numdfptr = DIM_NUM_DF_ELS(set_id_ndx); } /* inquire values of dimension for number of entities in set */ if (ex_get_dimension(exoid, numentryptr,"entries", &lnum_entry_in_set, &dimid, "ex_get_set_param") != NC_NOERR) return EX_FATAL; *num_entry_in_set = lnum_entry_in_set; /* Inquire value of dimension of number of dist factors for this set. NOTE: For node sets, because DIM_NUM_DF_NS is not used, we check to see if the dist factor variable for a node set index exits. If it does not, the dist factor count is assumed to be zero, otherwise the dist factor count will be the same as the number of nodes in the set. */ if (set_type == EX_NODE_SET) { if ((status = nc_inq_varid(exoid, VAR_FACT_NS(set_id_ndx), &varid)) != NC_NOERR) { *num_dist_fact_in_set = 0; /* signal dist factor doesn't exist */ if (status == NC_ENOTVAR) return (EX_NOERR); else { exerrval = status; sprintf(errmsg, "Error: failed to locate the dist factors for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set_param",errmsg,exerrval); return (EX_FATAL); } } *num_dist_fact_in_set = lnum_entry_in_set; /* # of df = # of nodes */ } else {/* all other set types */ if ((status = nc_inq_dimid(exoid, numdfptr, &dimid)) != NC_NOERR) { *num_dist_fact_in_set = 0; /* no distribution factors for this set*/ if (status == NC_EBADDIM) return (EX_NOERR); else { exerrval = status; sprintf(errmsg, "Error: failed to locate number of dist factors in %s %d in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_get_set_param",errmsg,exerrval); return (EX_FATAL); } } if ((status = nc_inq_dimlen(exoid, dimid, &lnum_dist_fact_in_set)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of dist factors in %s %d in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_get_set_param",errmsg,exerrval); return (EX_FATAL); } *num_dist_fact_in_set = lnum_dist_fact_in_set; } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expfrm.c0000755000175000017500000001413111606020250022256 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /*! * * expfrm - ex_put_coordinate_frames: write coordinate frames * * \param exoid exodus file id * \param nframes number of coordinate frames in model * \param cf_ids coordinate ids * \param pt_coordinates pointer to coordinates. 9 values per coordinate frame * \param tags character tag for each frame. 'r' - rectangular, 'c' - cylindrical, 's' - spherical * * returns - * EX_NOERR for no error * EX_FATAL for fatal errors * 1 number frames < 0 * *****************************************************************************/ #include #include #include "exodusII.h" #include "exodusII_int.h" /* -------------------- local defines --------------------------- */ #define PROCNAME "ex_put_coordinate_frames" /* -------------------- end of local defines -------------------- */ int ex_put_coordinate_frames( int exoid, int nframes, const int cf_ids[], void* pt_coordinates, const char* tags) { int status; int dim, dim9; /* dimension id for nframes, nframes*9 */ char errmsg[MAX_ERR_LENGTH]; /* buffer for error messages */ int varcoords; /* variable id for the coordinates */ int varids; /* variable id for the frame ids */ int vartags; /* variable id for the frame tags */ int i; /* general indices */ if ( exoid < 0 ) return exoid; if ( nframes == 0 ) /* write nothing */ return (EX_NOERR); if ( nframes<0 ) return 1; assert( cf_ids!=0 ); assert( pt_coordinates !=0 ); assert( tags != 0 ); /* make the definitions */ /* go into define mode. define num_frames, num_frames9 */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to place file id %d into define mode", exoid); ex_err(PROCNAME,errmsg,exerrval); return (EX_FATAL); } if ((status = nc_def_dim(exoid, NUM_CFRAMES, nframes, &dim)) != NC_NOERR || (nc_def_dim(exoid, NUM_CFRAME9, nframes*9, &dim9) != NC_NOERR)) { exerrval = status; sprintf(errmsg, "Error: failed to define number of coordinate frames in file id %d", exoid); ex_err(PROCNAME,errmsg,exerrval); goto error_ret; } /* define the variables. coordinates, tags and ids */ if (nc_def_var (exoid, FRAME_COORDS, nc_flt_code(exoid), 1, &dim9, &varcoords) != NC_NOERR || (nc_def_var(exoid, FRAME_IDS,NC_INT, 1, &dim, &varids) != NC_NOERR) || (nc_def_var(exoid, FRAME_TAGS,NC_CHAR,1,&dim, &vartags) != NC_NOERR) ) { exerrval = EX_FATAL; sprintf(errmsg, "Error: failed to define coordinate frames in file id %d", exoid); ex_err(PROCNAME,errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete coordinate frame definition in file id %d", exoid); ex_err(PROCNAME,errmsg,exerrval); return (EX_FATAL); } /* check variables consistency */ exerrval = EX_NOERR; for (i=0;i #include "exodusII.h" #include "exodusII_int.h" /* * reads the names of the property arrays from the database */ int ex_get_prop_names (int exoid, ex_entity_type obj_type, char **prop_names) { int status; int i, num_props, propid; char var_name[12]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* determine which type of object property names are desired for */ num_props = ex_get_num_props (exoid, obj_type); for (i=0; i /*! * writes the QA records to the database * \param exoid exodus file id * \param num_qa_records number of qa records to be written * \param *qa_record qa record array */ int ex_put_qa (int exoid, int num_qa_records, char* qa_record[][4]) { int status; int i, j, strdim, num_qa_dim, varid, n4dim; int dims[3]; size_t start[3], count[3]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* only do this if there are records */ if (num_qa_records > 0) { /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_STR, &strdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate string length in file id %d", exoid); ex_err("ex_put_qa",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_dimid(exoid, DIM_N4, &n4dim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate record length in file id %d", exoid); ex_err("ex_put_qa",errmsg,exerrval); return (EX_FATAL); } /* put file into define mode */ if ((status = nc_redef(exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_qa",errmsg,exerrval); return (EX_FATAL); } /* define dimensions */ if ((status = nc_def_dim(exoid,DIM_NUM_QA,num_qa_records, &num_qa_dim)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { /* duplicate entry? */ exerrval = status; sprintf(errmsg, "Error: qa records already exist in file id %d", exoid); ex_err("ex_put_qa",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define qa record array size in file id %d", exoid); ex_err("ex_put_qa",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } /* define variable */ dims[0] = num_qa_dim; dims[1] = n4dim; dims[2] = strdim; if ((status = nc_def_var(exoid, VAR_QA_TITLE, NC_CHAR, 3, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define qa record array in file id %d", exoid); ex_err("ex_put_qa",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete definition in file id %d", exoid); ex_err("ex_put_qa",errmsg,exerrval); return (EX_FATAL); } /* write out QA records */ for (i=0; i /* for free() */ /*! * writes the connectivity array for an element block * \param exoid exodus file id * \param elem_blk_id element block id * \param *connect connectivity array * \deprecated Use ex_put_conn()(exoid, EX_ELEM_BLOCK, elem_blk_id, connect, 0, 0) */ int ex_put_elem_conn (int exoid, int elem_blk_id, const int *connect) { return ex_put_conn(exoid, EX_ELEM_BLOCK, elem_blk_id, connect, 0, 0); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvarnams.c0000644000175000017500000001175011606020250023131 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * ex_get_variable_names * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type type of object * int num_vars # of variables to read * * exit conditions - * char* var_names ptr array of variable names * * revision history - * * $Id: exgvarnams.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * reads the names of the results variables from the database */ int ex_get_variable_names (int exoid, ex_entity_type obj_type, int num_vars, char *var_names[]) { int i, varid, status; char errmsg[MAX_ERR_LENGTH]; const char* vvarname; exerrval = 0; /* clear error code */ switch (obj_type) { case EX_NODAL: vvarname = VAR_NAME_NOD_VAR; break; case EX_EDGE_BLOCK: vvarname = VAR_NAME_EDG_VAR; break; case EX_FACE_BLOCK: vvarname = VAR_NAME_FAC_VAR; break; case EX_ELEM_BLOCK: vvarname = VAR_NAME_ELE_VAR; break; case EX_NODE_SET: vvarname = VAR_NAME_NSET_VAR; break; case EX_EDGE_SET: vvarname = VAR_NAME_ESET_VAR; break; case EX_FACE_SET: vvarname = VAR_NAME_FSET_VAR; break; case EX_SIDE_SET: vvarname = VAR_NAME_SSET_VAR; break; case EX_ELEM_SET: vvarname = VAR_NAME_ELSET_VAR; break; case EX_GLOBAL: vvarname = VAR_NAME_GLO_VAR; break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Warning: invalid variable type %d requested from file id %d", obj_type, exoid); ex_err("ex_get_var_param",errmsg,exerrval); return (EX_WARN); } /* inquire previously defined variables */ if ((status = nc_inq_varid(exoid, vvarname, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no %s variables names stored in file id %d", ex_name_of_object(obj_type),exoid); ex_err("ex_get_variable_names",errmsg,exerrval); return (EX_WARN); } /* read the variable names */ /* * See if reading into contiguous memory in which case we can load * all values in one call. If not, we must load each name individually. */ if ((size_t)(&var_names[num_vars-1][0] - &var_names[0][0]) == sizeof(char)*(MAX_STR_LENGTH+1)*(num_vars-1)) { status = nc_get_var_text(exoid, varid, &var_names[0][0]); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get results variable names from file id %d", exoid); ex_err("ex_get_var_names",errmsg,exerrval); return (EX_FATAL); } } else { for (i=0; i #include /* for malloc(), free() */ #define EX_TEST_FILENAME "edgeFace.exo" #define EXCHECK(funcall,errmsg)\ if ( (funcall) < 0 ) \ { \ fprintf( stderr, errmsg ); \ return 1; \ } #define EXCHKPI(funcall,errmsg,sucmsg,ival)\ if ( (funcall) < 0 ) \ { \ fprintf( stderr, errmsg ); \ return 1; \ } else { \ fprintf( stdout, sucmsg, ival ); \ } int obj_types[] = { EX_EDGE_BLOCK, EX_FACE_BLOCK, EX_ELEM_BLOCK, EX_NODE_SET, EX_EDGE_SET, EX_FACE_SET, EX_SIDE_SET, EX_ELEM_SET, EX_NODE_MAP, EX_EDGE_MAP, EX_FACE_MAP, EX_ELEM_MAP }; int obj_sizes[] = { EX_INQ_EDGE_BLK, EX_INQ_FACE_BLK, EX_INQ_ELEM_BLK, EX_INQ_NODE_SETS, EX_INQ_EDGE_SETS, EX_INQ_FACE_SETS, EX_INQ_SIDE_SETS, EX_INQ_ELEM_SETS, EX_INQ_NODE_MAP, EX_INQ_EDGE_MAP, EX_INQ_FACE_MAP, EX_INQ_ELEM_MAP, }; const char* obj_typenames[] = { " Edge block", " Face block", "Element block", " Node set", " Edge set", " Face set", " Side set", " Element set", " Node map", " Edge map", " Face map", " Element map" }; const char* obj_typestr[] = { "L", "F", "E", "M", "D", "A", "S", "T", 0, /* maps have no result variables */ 0, 0, 0, }; int obj_sizeinq[] = { EX_INQ_EDGE, EX_INQ_FACE, EX_INQ_ELEM, EX_INQ_NS_NODE_LEN, EX_INQ_ES_LEN, EX_INQ_FS_LEN, EX_INQ_SS_ELEM_LEN, EX_INQ_ELS_LEN, -1, -1, -1, -1 }; #define OBJECT_IS_BLOCK(i) ((i>=0)&&(i<3)) #define OBJECT_IS_SET(i) ((i>2)&&(i<8)) int cReadEdgeFace( int argc, char* argv[] ) { int exoid; int appWordSize = 8; int diskWordSize = 8; float exoVersion; int itmp[5]; int* ids; int nids; int obj; int i, j; int num_timesteps; int ti; char** obj_names; char** var_names; int have_var_names; int num_vars; /* number of variables per object */ int num_entries; /* number of values per variable per object */ double* entry_vals; /* variable values for each entry of an object */ ex_init_params modelParams; (void)argc; (void)argv; exoid = ex_open( EX_TEST_FILENAME, EX_READ, &appWordSize, &diskWordSize, &exoVersion ); if ( exoid <= 0 ) { fprintf( stderr, "Unable to open \"%s\" for reading.\n", EX_TEST_FILENAME ); return 1; } EXCHECK( ex_get_init_ext( exoid, &modelParams ), "Unable to read database parameters.\n" ); fprintf( stdout, "Title: <%s>\n" "Dimension: %d\n" "Nodes: %d\n" "Edges: %d\n" "Faces: %d\n" "Elements: %d\n" "Edge Blocks: %d\n" "Face Blocks: %d\n" "Element Blocks: %d\n" "Node Sets: %d\n" "Edge Sets: %d\n" "Face Sets: %d\n" "Side Sets: %d\n" "Element Sets: %d\n" "Node Maps: %d\n" "Edge Maps: %d\n" "Face Maps: %d\n" "Element Maps: %d\n", modelParams.title, modelParams.num_dim, modelParams.num_nodes, modelParams.num_edge, modelParams.num_face, modelParams.num_elem, modelParams.num_edge_blk, modelParams.num_face_blk, modelParams.num_elem_blk, modelParams.num_node_sets, modelParams.num_edge_sets, modelParams.num_face_sets, modelParams.num_side_sets, modelParams.num_elem_sets, modelParams.num_node_maps, modelParams.num_edge_maps, modelParams.num_face_maps, modelParams.num_elem_maps ); /* *** NEW API *** */ EXCHKPI( ex_inquire( exoid, EX_INQ_EDGE, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_EDGE : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_EDGE_BLK, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_EDGE_BLK : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_EDGE_SETS, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_EDGE_SETS : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_ES_LEN, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_ES_LEN : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_ES_DF_LEN, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_ES_DF_LEN : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_EDGE_PROP, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_EDGE_PROP : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_ES_PROP, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_ES_PROP : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_FACE, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_FACE : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_FACE_BLK, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_FACE_BLK : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_FACE_SETS, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_FACE_SETS : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_FS_LEN, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_FS_LEN : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_FS_DF_LEN, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_FS_DF_LEN : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_FACE_PROP, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_FACE_PROP : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_FS_PROP, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_FS_PROP : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_ELEM_SETS, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_ELEM_SETS : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_ELS_LEN, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_ELS_LEN : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_ELS_DF_LEN, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_ELS_DF_LEN : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_ELS_PROP, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_ELS_PROP : %d\n", itmp[0] ); EXCHKPI( ex_inquire( exoid, EX_INQ_TIME, itmp, 0, 0 ), "Inquire failed.\n", "EX_INQ_TIME : %d\n", itmp[0] ); num_timesteps = itmp[0]; /* *** NEW API *** */ for ( i = 0; i < (int)(sizeof(obj_types)/sizeof(obj_types[0])); ++i ) { int* truth_tab = 0; have_var_names = 0; EXCHECK( ex_inquire( exoid, obj_sizes[i], &nids, 0, 0 ), "Object ID list size could not be determined.\n" ); if ( ! nids ) { fprintf( stdout, "=== %ss: none\n\n", obj_typenames[i] ); continue; } else { fprintf( stdout, "=== %ss: %d\n", obj_typenames[i], nids ); } ids = (int*) malloc( nids * sizeof(int) ); obj_names = (char**) malloc( nids * sizeof(char*) ); for ( obj = 0; obj < nids; ++obj ) obj_names[obj] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); EXCHECK( ex_get_ids( exoid, obj_types[i], ids ), "Could not read object ids.\n" ); EXCHECK( ex_get_names( exoid, obj_types[i], obj_names ), "Could not read object ids.\n" ); if ( (OBJECT_IS_BLOCK(i)) || (OBJECT_IS_SET(i)) ) { int* tp; EXCHECK( ex_get_var_param( exoid, obj_typestr[i], &num_vars ), "Could not read number of variables.\n" ); if ( num_vars && num_timesteps > 0 ) { truth_tab = (int*) malloc( num_vars * nids * sizeof(int) ); EXCHECK( ex_get_var_tab( exoid, obj_typestr[i], nids, num_vars, truth_tab ), "Could not read truth table.\n" ); tp = truth_tab; fprintf( stdout, "Truth:" ); for ( obj = 0; obj < nids; ++obj ) { for ( j = 0; j < num_vars; ++j, ++tp ) { fprintf( stdout, " %d", *tp ); } fprintf( stdout, "\n " ); } fprintf( stdout, "\n" ); var_names = (char**) malloc( num_vars * sizeof(char*) ); for ( j = 0; j < num_vars; ++j ) var_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); EXCHECK( ex_get_var_names( exoid, obj_typestr[i], num_vars, var_names ), "Could not read variable names.\n" ); have_var_names = 1; } } if ( ! have_var_names ) var_names = 0; for ( obj = 0; obj < nids; ++obj ) { if ( obj_names[obj] ) fprintf( stdout, "%s %3d (%s): ", obj_typenames[i], ids[obj], obj_names[obj] ); else fprintf( stdout, "%s %3d: ", obj_typenames[i], ids[obj] ); if ( OBJECT_IS_BLOCK(i) ) { int* nconn; int* econn; int* fconn; int ele; int ctr; int num_attrs; if ( obj_types[i] == EX_ELEM_BLOCK ) { EXCHECK( ex_get_block( exoid, obj_types[i], ids[obj], 0, itmp, itmp+1, itmp+2, itmp+3, &num_attrs ), "Could not read block params.\n" ); fprintf( stdout, "Entries: %3d Nodes/entry: %d Edges/entry: %d Faces/entry: %d Attributes: %d", itmp[0], itmp[1], itmp[2], itmp[3], num_attrs ); } else { EXCHECK( ex_get_block( exoid, obj_types[i], ids[obj], 0, itmp, itmp+1, 0, 0, &num_attrs ), "Could not read block params.\n" ); fprintf( stdout, "Entries: %3d Nodes/entry: %d Attributes: %d", itmp[0], itmp[1], num_attrs ); itmp[2] = itmp[3] = 0; } fprintf( stdout, "\n " ); num_entries = itmp[0]; nconn = itmp[1] ? (int*) malloc( itmp[1] * num_entries * sizeof(int) ) : 0; econn = itmp[2] ? (int*) malloc( itmp[2] * num_entries * sizeof(int) ) : 0; fconn = itmp[3] ? (int*) malloc( itmp[3] * num_entries * sizeof(int) ) : 0; EXCHECK( ex_get_conn( exoid, obj_types[i], ids[obj], nconn, econn, fconn ), "Could not read connectivity.\n" ); for ( ele = 0; ele < num_entries; ++ele ) { for ( ctr = 0; ctr < itmp[1]; ++ctr ) { fprintf( stdout, " %2d", nconn[ele*itmp[1] + ctr] ); } if ( itmp[2] ) { fprintf( stdout, " ++" ); for ( ctr = 0; ctr < itmp[2]; ++ctr ) { fprintf( stdout, " %2d", econn[ele*itmp[2] + ctr] ); } } if ( itmp[3] ) { fprintf( stdout, " ++" ); for ( ctr = 0; ctr < itmp[3]; ++ctr ) { fprintf( stdout, " %2d", fconn[ele*itmp[3] + ctr] ); } } fprintf( stdout, "\n " ); } if ( nconn ) free( nconn ); if ( econn ) free( econn ); if ( fconn ) free( fconn ); if ( num_attrs ) { char** attr_names; double* attr; attr = (double*) malloc( num_entries * num_attrs * sizeof(double) ); attr_names = (char**) malloc( num_attrs * sizeof(char*) ); for ( j = 0; j < num_attrs; ++j ) attr_names[j] = (char*) malloc( (MAX_STR_LENGTH + 1) * sizeof(char) ); EXCHECK( ex_get_attr_names( exoid, obj_types[i], ids[obj], attr_names ), "Could not read attributes names.\n" ); EXCHECK( ex_get_attr( exoid, obj_types[i], ids[obj], attr ), "Could not read attribute values.\n" ); fprintf( stdout, "\n Attributes:\n ID " ); for ( j = 0; j < num_attrs; ++j ) fprintf( stdout, " %s", attr_names[j] ); fprintf( stdout, "\n" ); for ( j = 0; j < num_entries; ++j ) { int k; fprintf( stdout, " %2d ", j + 1 ); for ( k = 0; k < num_attrs; ++k ) { fprintf( stdout, " %4.1f", attr[ j * num_attrs + k ] ); } fprintf( stdout, "\n" ); } for ( j = 0; j < num_attrs; ++j ) free( attr_names[j] ); free( attr_names ); free( attr ); } } else if ( OBJECT_IS_SET(i) ) { int num_df; int* set_entry; int* set_extra; double* set_df; EXCHECK( ex_get_set_param( exoid, obj_types[i], ids[obj], &num_entries, &num_df ), "Could not read set parameters.\n" ); set_entry = (int*) malloc( num_entries * sizeof(int) ); set_extra = ( obj_types[i] != EX_NODE_SET && obj_types[i] != EX_ELEM_SET ) ? (int*) malloc( num_entries * sizeof(int) ) : 0; EXCHECK( ex_get_set( exoid, obj_types[i], ids[obj], set_entry, set_extra ), "Could not read set.\n" ); fprintf( stdout, "Entries: %3d Distribution factors: %3d\n", num_entries, num_df ); if ( set_extra ) { for ( j = 0; j < num_entries; ++j ) fprintf( stdout, " %2d %2d\n", set_entry[j], set_extra[j] ); } else { for ( j = 0; j < num_entries; ++j ) fprintf( stdout, " %2d\n", set_entry[j] ); } free( set_entry ); if ( set_extra ) free( set_extra ); set_df = num_df ? (double*) malloc( num_df * sizeof(double) ) : 0; if ( set_df ) { EXCHECK( ex_get_set_dist_fact( exoid, obj_types[i], ids[obj], set_df ), "Could not read set distribution factors.\n" ); fprintf( stdout, "\n Distribution factors:\n" ); for ( j = 0; j < num_df; ++j ) fprintf( stdout, " %4.1f\n", set_df[j] ); free( set_df ); } } else { /* object is map */ int* map; switch (obj_types[i]) { case EX_NODE_MAP: num_entries = modelParams.num_nodes; break; case EX_EDGE_MAP: num_entries = modelParams.num_edge; break; case EX_FACE_MAP: num_entries = modelParams.num_face; break; case EX_ELEM_MAP: num_entries = modelParams.num_elem; break; } if ( num_entries ) { fprintf( stdout, "Entries: %3d\n :", num_entries ); map = (int*) malloc( num_entries * sizeof(int) ); EXCHECK( ex_get_num_map( exoid, obj_types[i], ids[obj], map ), "Could not read map.\n" ); for ( j = 0; j < num_entries; ++j ) { fprintf( stdout, " %d", map[j] ); } } else { fprintf( stdout, "Entries: none" ); } } fprintf( stdout, "\n" ); /* Read results variables */ if ( ((OBJECT_IS_BLOCK(i)) || (OBJECT_IS_SET(i))) && num_vars && num_timesteps > 0 ) { /* Print out all the time values to exercise get_var */ entry_vals = (double*) malloc( num_entries * sizeof(double) ); for ( j = 0; j < num_vars; ++j ) { int k; if ( ! truth_tab[num_vars * obj + j] ) continue; fprintf( stdout, " Variable: %s", var_names[j] ); for ( ti = 1; ti <= num_timesteps; ++ti ) { EXCHECK( ex_get_var( exoid, ti, obj_types[i], 1 + j, ids[obj], num_entries, entry_vals ), "Could not read variable values.\n" ); fprintf( stdout, "\n @t%d ", ti ); for ( k = 0; k < num_entries; ++k ) { fprintf( stdout, " %4.1f", entry_vals[k] ); } } fprintf( stdout, "\n" ); } fprintf( stdout, "\n" ); free( entry_vals ); } } if ( ((OBJECT_IS_BLOCK(i)) || (OBJECT_IS_SET(i))) && num_vars && num_timesteps > 0 ) { /* Print out one element's time values to exercise get_var_time */ entry_vals = (double*) malloc( num_timesteps * sizeof( double ) ); EXCHECK( ex_inquire( exoid, obj_sizeinq[i], itmp, 0, 0 ), "Inquire failed.\n" ); itmp[1] = 11; while ( itmp[1] > itmp[0] ) itmp[1] /= 2; for ( j = 0; j < num_vars; ++j ) { /* FIXME: This works for the dataset created by CreateEdgeFace, but not for any dataset in general since * NULL truth table entries may mean the referenced elements don't have variable values. */ EXCHECK( ex_get_var_time( exoid, obj_types[i], j + 1, itmp[1], 1, num_timesteps, entry_vals ), "Could not read variable over time.\n" ); fprintf( stdout, " Variable over time: %s Entry: %3d ", var_names[j], itmp[1] ); for ( ti = 1; ti <= num_timesteps; ++ti ) fprintf( stdout, " @t%d: %4.1f", ti, entry_vals[ti-1] ); fprintf( stdout, "\n" ); } free( entry_vals ); } if ( var_names ) { for ( j = 0; j < num_vars; ++j ) free( var_names[j] ); free( var_names ); } if ( truth_tab ) free( truth_tab ); free( ids ); for ( obj = 0; obj < nids; ++obj ) free( obj_names[obj] ); free( obj_names ); fprintf( stdout, "\n" ); } EXCHECK( ex_close( exoid ), "Unable to close database.\n" ); return 0; } #ifndef EXO_CTEST int main( int argc, char* argv[] ) { return cReadEdgeFace(argc, argv); } #endif /* EXO_CTEST */ xdmf-2.1.dfsg.1/Utilities/vtkexodus2/test/CVS/0000755000175000017500000000000011606020250022220 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtkexodus2/test/CVS/Entries0000644000175000017500000000022111606020250023547 0ustar amckinstryamckinstry/CMakeLists.txt/1.1/Wed Jan 6 16:33:54 2010// /CreateEdgeFace.c/1.1/Wed Jan 6 16:33:58 2010// /ReadEdgeFace.c/1.1/Wed Jan 6 16:34:00 2010// D xdmf-2.1.dfsg.1/Utilities/vtkexodus2/test/CVS/Repository0000644000175000017500000000003711606020250024322 0ustar amckinstryamckinstryXdmf/Utilities/vtkexodus2/test xdmf-2.1.dfsg.1/Utilities/vtkexodus2/test/CVS/Root0000644000175000017500000000006411606020250023066 0ustar amckinstryamckinstry:pserver:anonymous@public.kitware.com:/cvsroot/Xdmf xdmf-2.1.dfsg.1/Utilities/vtkexodus2/test/CMakeLists.txt0000644000175000017500000000201411606020250024322 0ustar amckinstryamckinstrySET( cbind_TEST_SRCS CreateEdgeFace.c ReadEdgeFace.c ) SET_SOURCE_FILES_PROPERTIES( CreateEdgeFace.c ReadEdgeFace.c COMPILE_FLAGS -DEXO_CTEST ) # Always report error/warning messages during testing: # The ex_opts call precipitates the EXTRA_INCLUDE below. SET( CMAKE_TESTDRIVER_BEFORE_TESTMAIN "${CMAKE_TESTDRIVER_BEFORE_TESTMAIN} ex_opts( EX_VERBOSE );\n" ) CREATE_TEST_SOURCELIST( ExoIICTests ExoIICTests.cxx ${cbind_TEST_SRCS} EXTRA_INCLUDE exodusII_test.h ) ADD_EXECUTABLE( ExoIICTests ${ExoIICTests} ) TARGET_LINK_LIBRARIES( ExoIICTests vtkCommon vtkexoIIc vtkNetCDF ) SET( TestsToRun ${ExoIICTests} ) REMOVE( TestsToRun ExoIICTests.cxx ) FOREACH( test ${TestsToRun} ) GET_FILENAME_COMPONENT(TName ${test} NAME_WE) ADD_TEST( ${TName} ${EXECUTABLE_OUTPUT_PATH}/ExoIICTests ${TName} ) ENDFOREACH( test ) ADD_TEST( CreateEdgeFaceWithConcats ${EXECUTABLE_OUTPUT_PATH}/ExoIICTests CreateEdgeFace -pcab -pcset -pvpax ) ADD_TEST( ReadEdgeFaceWithConcats ${EXECUTABLE_OUTPUT_PATH}/ExoIICTests ReadEdgeFace ) xdmf-2.1.dfsg.1/Utilities/vtkexodus2/test/CreateEdgeFace.c0000644000175000017500000005235011606020250024505 0ustar amckinstryamckinstry#include "exodusII.h" #include #include #define EX_TEST_FILENAME "edgeFace.exo" /* ======== Coordinates and connectivity ========= */ double coordsX[] = { 0., 0., 0., 0., 3., 3., 3., 3., -3., -3., -3., -3. }; double coordsY[] = { -1., 1., 1., -1., -3., 3., 3., -3., -3., 3., 3., -3. }; double coordsZ[] = { -1., -1., 1., 1., -3., -3., 3., 3., -3., -3., 3., 3. }; char* coordsNames[] = { "X", "Y", "Z" }; int conn1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4 }; int conn2[] = { 1, 2, 3, 5 }; int econn1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 17, 18, 19, 20 }; int fconn1[] = { 4, 5, 7, 6, 3, 2, 8, 9, 11, 10, 1, 3 }; int ebconn1[] = { 1, 2, 2, 3, 3, 4, 4, 1, 5, 6, 6, 7, 7, 8, 8, 5, 1, 5, 2, 6, 4, 8, 3, 7, 9, 10, 10, 11, 11, 12, 12, 9, 9, 1, 10, 2, 12, 4, 11, 3 }; int fbconn1[] = { 12, 11, 10, 9, 5, 6, 7, 8 }; int fbconn2[] = { 1, 2, 3, 4 }; int fbconn3[] = { 1, 5, 6, 2, 3, 7, 8, 4, 2, 6, 7, 3, 4, 8, 5, 1, 9, 1, 2, 10, 11, 3, 4, 12, 10, 2, 3, 11, 12, 4, 1, 9 }; int nmap1[] = { 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; int edmap1[] = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; int famap1[] = { 2, 1, 4, 3, 6, 5, 7, 8, 9, 10, 11 }; int emap1[] = { 1, 2, 3 }; char* eblk_names[] = { "Eli WALLACH", "Angelo NOVI" }; char* edblk_names[] = { "Aldo GIUFFRE" }; char* fablk_names[] = { "Livio LORENZON", "Claudio SCARCHILLI", "John BARTHA" }; char* nmap_names[] = { "Luigi PISTILLI" }; char* edmap_names[] = { "Antonio CASALE" }; char* famap_names[] = { "Sandro SCARCHILLI" }; char* emap_names[] = { "Benito STEFANELLI" }; /* ======== Sets ========= */ int nset_nodes[] = { 5, 6, 9 }; int eset_edges[] = { 1, 2, 4, 15, 19, 20 }; int eset_orient[] = { +1, +1, +1, +1, +1, -1 }; double eset_df[] = { 2., 2., 0.5, 0.5, 1., 1. }; int fset_faces[] = { 3, 9 }; int fset_orient[] = { +1, -1 }; int sset_elems[] = { 1, 1, 1, 2, 2 }; int sset_sides[] = { 1, 3, 5, 2, 4 }; int elset_elems[] = { 1, 2 }; char* elset_names[] = { "Clint EASTWOOD", "Lee VAN CLEEF" }; char* nset_names[] = { "Ennio MORRICONE" }; char* eset_names[] = { "Rada RASSIMOV" }; char* fset_names[] = { "Enzo PETITO" }; char* sset_names[] = { "Luciano VINCENZONI" }; /* ======== Attributes ========= */ char* edge_attr_names1[] = {"Sergio LEONE"}; char* face_attr_names1[] = {"GOOD"}; char* face_attr_names2[] = {"BAD"}; char* face_attr_names3[] = {"UGLY"}; char* elem_attr_names1[] = { "SPAGHETTI", "WESTERN" }; double edge_attr_values1[] = { 1., 2., 3., 5., 7., 11., 13., 17., 19., 23., 29., 31., 37., 41., 43., 47., 53., 59., 61., 67. }; double face_attr_values1[] = { 71., 73. }; double face_attr_values2[] = { 79. }; double face_attr_values3[] = { 83., 89., 97., 101., 103., 107., 109., 113. }; double elem_attr_values1[] = { 127., 101., 137., 139. }; /* ======== Results variables ========= */ /* (2 time steps) */ double vals_glo_var[2][2] = { { 36., 37. }, { 42., 43. } }; double vals_nod_var[2][12] = { { 0.1, 0.8, 0.0, 0.4, 0.3, 0.9, 0.8, 0.5, 0.3, 0.7, 0.4, 0.6 }, { 0.7, 0.5, 0.3, 0.5, 0.2, 0.7, 0.9, 0.8, 0.0, 0.2, 0.3, 0.5 } } ; double vals_edge_var1eb1[2][20] = { { 20., 19., 18., 17., 16., 15., 14., 13., 12., 11., 10., 9., 8., 7., 6., 5., 4., 3., 2., 1. }, { 21., 20., 19., 18., 17., 16., 15., 14., 13., 12., 11., 10., 9., 8., 7., 6., 5., 4., 3., 2. } }; double vals_edge_var2eb1[2][20] = { { 1., 1., 0., 0., 1., 1., 2., 0., 2., 0., 1., 1., 1., 1., 0., 0., 2., 2., 2., 2. }, { 1., 1., 0., 0., 1., 1., 2., 0., 2., 0., 1., 1., 1., 1., 0., 0., 2., 2., 2., 2. } }; double vals_face_var1fb1[2][2] = { { 0, 1 }, { 2, 0 } }; double vals_face_var1fb3[2][8] = { { 1, 0, 2, 0, 3, 0, 4, 0 }, { 0, 1, 0, 2, 0, 3, 0, 4 } }; double vals_elem_var1eb1[2][2] = { { 8, 8 }, { 0, -8 } }; double vals_fset_var1fs1[2][2] = { { 1., 3. }, { 9., 27. } }; #define EXCHECK(funcall,errmsg)\ if ( (funcall) < 0 ) \ { \ fprintf( stderr, errmsg ); \ return 1; \ } int ex_have_arg( int argc, char* argv[], const char* aname ) { int i; for ( i = 0; i < argc; ++i ) if ( ! strcmp( argv[i], aname ) ) return 1; return 0; } int cCreateEdgeFace( int argc, char* argv[] ) { int exoid; int appWordSize = 8; int diskWordSize = 8; int concatBlocks = ex_have_arg( argc, argv, "-pcab" ); int concatSets = ex_have_arg( argc, argv, "-pcset" ); int concatResult = ex_have_arg( argc, argv, "-pvpax" ); double t; ex_init_params modelParams = { "CreateEdgeFace Test", /* title */ 3, /* num_dim */ 12, /* num_nodes */ 20, /* num_edge */ 1, /* num_edge_blk */ 11, /* num_face */ 3, /* num_face_blk */ 3, /* num_elem */ 2, /* num_elem_blk */ 1, /* num_node_sets */ 1, /* num_edge_sets */ 1, /* num_face_sets */ 1, /* num_side_sets */ 2, /* num_elem_sets */ 1, /* num_node_map */ 1, /* num_edge_map */ 1, /* num_face_map */ 1, /* num_elem_map */ }; ex_block_params blockParams = { (int[]){ 100 }, /* edge_blk_id */ (char*[]){ "STRAIGHT2" }, /* edge_type */ (int[]){ 20 }, /* num_edge_this_blk */ (int[]){ 2 }, /* num_nodes_per_edge */ (int[]){ 1 }, /* num_attr_edge */ (int[]){ 500, 600, 700 }, /* face_blk_id */ (char*[]){ "QUAD4", "QUAD4", "QUAD4" }, /* face_type */ (int[]){ 2, 1, 8 }, /* num_face_this_blk */ (int[]){ 4, 4, 4 }, /* num_nodes_per_face */ (int[]){ 1, 1, 1 }, /* num_attr_face */ (int[]){ 200, 201 }, /* elem_blk_id */ (char*[]){ "HEX8", "TET4" }, /* elem_type */ (int[]){ 2, 1 }, /* num_elem_this_blk */ (int[]){ 8, 4 }, /* num_nodes_per_elem */ (int[]){ 12, 0 }, /* num_edges_per_elem */ (int[]){ 6, 0 }, /* num_faces_per_elem */ (int[]){ 2, 0 }, /* num_attr_elem */ 0 /* define_maps */ }; ex_var_params varParams = { (int) 2, /* num_glob */ (int) 1, /* num_node */ (int) 2, /* num_edge */ (int[]) { 1, 1 }, /* edge_var_tab */ (int) 1, /* num_face */ (int[]) { 1, 0, 1 }, /* face_var_tab */ (int) 1, /* num_elem */ (int[]) { 1, 0 }, /* elem_var_tab */ (int) 0, /* num_nset */ (int[]) {}, /* nset_var_tab */ (int) 0, /* num_eset */ (int[]) {}, /* eset_var_tab */ (int) 1, /* num_fset */ (int[]) { 1 }, /* fset_var_tab */ (int) 0, /* num_sset */ (int[]) {}, /* sset_var_tab */ (int) 0, /* num_elset */ (int[]) {} /* elset_var_tab */ }; exoid = ex_create( EX_TEST_FILENAME, EX_CLOBBER, &appWordSize, &diskWordSize ); if ( exoid <= 0 ) { fprintf( stderr, "Unable to open \"%s\" for writing.\n", EX_TEST_FILENAME ); return 1; } /* *** NEW API *** */ EXCHECK( ex_put_init_ext( exoid, &modelParams ), "Unable to initialize database.\n" ); /* *** NEW API *** */ if ( concatBlocks ) { EXCHECK( ex_put_concat_all_blocks( exoid, &blockParams ), "Unable to initialize block params.\n" ); } else { int blk; for ( blk = 0; blk < modelParams.num_edge_blk; ++blk ) { EXCHECK( ex_put_block( exoid, EX_EDGE_BLOCK, blockParams.edge_blk_id[blk], blockParams.edge_type[blk], blockParams.num_edge_this_blk[blk], blockParams.num_nodes_per_edge[blk], 0, 0, blockParams.num_attr_edge[blk] ), "Unable to write edge block" ); } for ( blk = 0; blk < modelParams.num_face_blk; ++blk ) { EXCHECK( ex_put_block( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[blk], blockParams.face_type[blk], blockParams.num_face_this_blk[blk], blockParams.num_nodes_per_face[blk], 0, 0, blockParams.num_attr_face[blk] ), "Unable to write face block" ); } for ( blk = 0; blk < modelParams.num_elem_blk; ++blk ) { EXCHECK( ex_put_block( exoid, EX_ELEM_BLOCK, blockParams.elem_blk_id[blk], blockParams.elem_type[blk], blockParams.num_elem_this_blk[blk], blockParams.num_nodes_per_elem[blk], blockParams.num_edges_per_elem[blk], blockParams.num_faces_per_elem[blk], blockParams.num_attr_elem[blk] ), "Unable to write elem block" ); } } EXCHECK( ex_put_coord( exoid, (void*)coordsX, (void*)coordsY, (void*)coordsZ ), "Unable to write coordinates.\n" ); EXCHECK( ex_put_coord_names( exoid, coordsNames ), "Unable to write coordinate names.\n" ); /* =============== Connectivity ================== */ /* *** NEW API *** */ EXCHECK( ex_put_conn( exoid, EX_EDGE_BLOCK, blockParams.edge_blk_id[0], ebconn1, 0, 0 ), "Unable to write edge block connectivity.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_conn( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[0], fbconn1, 0, 0 ), "Unable to write face block 1 connectivity.\n" ); EXCHECK( ex_put_conn( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[1], fbconn2, 0, 0 ), "Unable to write face block 2 connectivity.\n" ); EXCHECK( ex_put_conn( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[2], fbconn3, 0, 0 ), "Unable to write face block 3 connectivity.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_conn( exoid, EX_ELEM_BLOCK, blockParams.elem_blk_id[0], conn1, econn1, fconn1 ), "Unable to write elem block 1 connectivity.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_conn( exoid, EX_ELEM_BLOCK, blockParams.elem_blk_id[1], conn2, 0, 0 ), "Unable to write elem block 2 connectivity.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_names( exoid, EX_EDGE_BLOCK, edblk_names ), "Unable to write edge block names.\n" ); EXCHECK( ex_put_names( exoid, EX_FACE_BLOCK, fablk_names ), "Unable to write face block names.\n" ); EXCHECK( ex_put_names( exoid, EX_ELEM_BLOCK, eblk_names ), "Unable to write element block names.\n" ); /* =============== Number Maps ================== */ /* *** NEW API *** */ EXCHECK( ex_put_num_map( exoid, EX_NODE_MAP, 300, nmap1 ), "Unable to write node map.\n" ); EXCHECK( ex_put_num_map( exoid, EX_EDGE_MAP, 800, edmap1 ), "Unable to write edge map.\n" ); EXCHECK( ex_put_num_map( exoid, EX_FACE_MAP, 900, famap1 ), "Unable to write face map.\n" ); EXCHECK( ex_put_num_map( exoid, EX_ELEM_MAP, 400, emap1 ), "Unable to write element map.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_names( exoid, EX_NODE_MAP, nmap_names ), "Unable to write node map names.\n" ); EXCHECK( ex_put_names( exoid, EX_EDGE_MAP, edmap_names ), "Unable to write edge map names.\n" ); EXCHECK( ex_put_names( exoid, EX_FACE_MAP, famap_names ), "Unable to write face map names.\n" ); EXCHECK( ex_put_names( exoid, EX_ELEM_MAP, emap_names ), "Unable to write element map names.\n" ); /* =============== Attribute names ================ */ /* *** NEW API *** */ EXCHECK( ex_put_attr_names( exoid, EX_EDGE_BLOCK, blockParams.edge_blk_id[0], edge_attr_names1 ), "Unable to write edge block 1 attribute names.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_attr_names( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[0], face_attr_names1 ), "Unable to write face block 1 attribute names.\n" ); EXCHECK( ex_put_attr_names( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[1], face_attr_names2 ), "Unable to write face block 1 attribute names.\n" ); EXCHECK( ex_put_attr_names( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[2], face_attr_names3 ), "Unable to write face block 1 attribute names.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_attr_names( exoid, EX_ELEM_BLOCK, blockParams.elem_blk_id[0], elem_attr_names1 ), "Unable to write elem block 1 attribute names.\n" ); /* =============== Attribute values =============== */ /* *** NEW API *** */ EXCHECK( ex_put_attr( exoid, EX_EDGE_BLOCK, blockParams.edge_blk_id[0], edge_attr_values1 ), "Unable to write edge block 1 attribute values.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_attr( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[0], face_attr_values1 ), "Unable to write face block 1 attribute values.\n" ); EXCHECK( ex_put_attr( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[1], face_attr_values2 ), "Unable to write face block 1 attribute values.\n" ); EXCHECK( ex_put_attr( exoid, EX_FACE_BLOCK, blockParams.face_blk_id[2], face_attr_values3 ), "Unable to write face block 1 attribute values.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_attr( exoid, EX_ELEM_BLOCK, blockParams.elem_blk_id[0], elem_attr_values1 ), "Unable to write elem block 1 attribute values.\n" ); /* =============== Set parameters ================= */ /* *** NEW API *** */ EXCHECK( ex_put_names( exoid, EX_NODE_SET, nset_names ), "Unable to write node set names.\n" ); EXCHECK( ex_put_names( exoid, EX_EDGE_SET, eset_names ), "Unable to write edge set names.\n" ); EXCHECK( ex_put_names( exoid, EX_FACE_SET, fset_names ), "Unable to write face set names.\n" ); EXCHECK( ex_put_names( exoid, EX_SIDE_SET, sset_names ), "Unable to write side set names.\n" ); EXCHECK( ex_put_names( exoid, EX_ELEM_SET, elset_names ), "Unable to write element set names.\n" ); if ( concatSets ) { ex_set_specs setParams; setParams = (ex_set_specs) { (int[]) {1000}, (int[]) {3}, (int[]) {0}, (int[]) {0}, (int[]) {0}, (int*) nset_nodes, (int*) 0, (void*) 0 }; EXCHECK( ex_put_concat_sets( exoid, EX_NODE_SET, &setParams ), "Unable to write node sets.\n" ); setParams = (ex_set_specs) { (int[]) {1200}, (int[]) {6}, (int[]) {6}, (int[]) {0}, (int[]) {0}, (int*) eset_edges, (int*) eset_orient, (void*) eset_df }; EXCHECK( ex_put_concat_sets( exoid, EX_EDGE_SET, &setParams ), "Unable to write edge sets.\n" ); setParams = (ex_set_specs) { (int[]) {1400}, (int[]) {2}, (int[]) {0}, (int[]) {0}, (int[]) {0}, (int*) fset_faces, (int*) fset_orient, (void*) 0 }; EXCHECK( ex_put_concat_sets( exoid, EX_FACE_SET, &setParams ), "Unable to write face sets.\n" ); setParams = (ex_set_specs) { (int[]) {1600}, (int[]) {5}, (int[]) {0}, (int[]) {0}, (int[]) {0}, (int*) sset_elems, (int*) sset_sides, (void*) 0 }; EXCHECK( ex_put_concat_sets( exoid, EX_SIDE_SET, &setParams ), "Unable to write side sets.\n" ); setParams = (ex_set_specs) { (int[]) {1800, 1900}, (int[]) {1, 1}, (int[]) {0, 0}, (int[]) {0, 1}, (int[]) {0, 0}, (int*) elset_elems, (int*) 0, (void*) 0 }; EXCHECK( ex_put_concat_sets( exoid, EX_ELEM_SET, &setParams ), "Unable to write element sets.\n" ); } else { /* *** NEW API *** */ EXCHECK( ex_put_set_param( exoid, EX_NODE_SET, 1000, 3, 0 ), "Unable to write node set params.\n" ); EXCHECK( ex_put_set( exoid, EX_NODE_SET, 1000, nset_nodes, 0 ), "Unable to write node set.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_set_param( exoid, EX_EDGE_SET, 1200, 6, 6 ), "Unable to write edge set params.\n" ); EXCHECK( ex_put_set( exoid, EX_EDGE_SET, 1200, eset_edges, eset_orient ), "Unable to write edge set.\n" ); EXCHECK( ex_put_set_dist_fact( exoid, EX_EDGE_SET, 1200, eset_df ), "Unable to write edge set dist factors.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_set_param( exoid, EX_FACE_SET, 1400, 2, 0 ), "Unable to write face set params.\n" ); EXCHECK( ex_put_set( exoid, EX_FACE_SET, 1400, fset_faces, fset_orient ), "Unable to write face set.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_set_param( exoid, EX_SIDE_SET, 1600, 5, 0 ), "Unable to write side set params.\n" ); EXCHECK( ex_put_set( exoid, EX_SIDE_SET, 1600, sset_elems, sset_sides ), "Unable to write side set.\n" ); /* *** NEW API *** */ EXCHECK( ex_put_set_param( exoid, EX_ELEM_SET, 1800, 1, 0 ), "Unable to write element set 1 params.\n" ); EXCHECK( ex_put_set( exoid, EX_ELEM_SET, 1800, elset_elems + 0, 0 ), "Unable to write element set 1.\n" ); EXCHECK( ex_put_set_param( exoid, EX_ELEM_SET, 1900, 1, 0 ), "Unable to write element set 2 params.\n" ); EXCHECK( ex_put_set( exoid, EX_ELEM_SET, 1900, elset_elems + 1, 0 ), "Unable to write element set 2.\n" ); } /* =============== Result variable params ========= */ /* *** NEW API *** */ if ( concatResult ) { EXCHECK( ex_put_all_var_param_ext( exoid, &varParams ), "Unable to write result variable parameter information.\n" ); } else { EXCHECK( ex_put_var_param( exoid, "G", 2 ), "Unable to write global result variable parameters.\n" ); EXCHECK( ex_put_var_param( exoid, "N", 1 ), "Unable to write nodal result variable parameters.\n" ); EXCHECK( ex_put_var_param( exoid, "E", 1 ), "Unable to write element result variable parameters.\n" ); EXCHECK( ex_put_var_param( exoid, "L", 2 ), "Unable to write edge result variable parameters.\n" ); EXCHECK( ex_put_var_param( exoid, "F", 1 ), "Unable to write face result variable parameters.\n" ); EXCHECK( ex_put_var_param( exoid, "A", 1 ), "Unable to write faceset result variable parameters.\n" ); } /* =============== Result variable names ========== */ /* *** NEW API *** */ EXCHECK( ex_put_var_name( exoid, "G", 1, "CALIBER" ), "Unable to write variable name.\n" ); EXCHECK( ex_put_var_name( exoid, "g", 2, "GUNPOWDER" ), "Unable to write variable name.\n" ); EXCHECK( ex_put_var_name( exoid, "N", 1, "RHO" ), "Unable to write variable name.\n" ); EXCHECK( ex_put_var_name( exoid, "l", 1, "GAMMA1" ), "Unable to write variable name.\n" ); EXCHECK( ex_put_var_name( exoid, "L", 2, "GAMMA2" ), "Unable to write variable name.\n" ); EXCHECK( ex_put_var_name( exoid, "f", 1, "PHI" ), "Unable to write variable name.\n" ); EXCHECK( ex_put_var_name( exoid, "E", 1, "EPSTRN" ), "Unable to write variable name.\n" ); EXCHECK( ex_put_var_name( exoid, "A", 1, "PHI0" ), "Unable to write variable name.\n" ); /* =============== Result variable values ========= */ t = 1.; /* *** NEW API *** */ EXCHECK( ex_put_time( exoid, 1, &t ), "Unable to write time value.\n" ); EXCHECK( ex_put_var( exoid, 1, EX_GLOBAL, 1, 0/*N/A*/, 2, vals_glo_var[0] ), "Unable to write global var 1.\n" ); EXCHECK( ex_put_var( exoid, 1, EX_EDGE_BLOCK, 1, 100, 20, vals_edge_var1eb1[0] ), "Unable to write edge block 1 var 1.\n" ); EXCHECK( ex_put_var( exoid, 1, EX_EDGE_BLOCK, 2, 100, 20, vals_edge_var2eb1[0] ), "Unable to write edge block 1 var 2.\n" ); EXCHECK( ex_put_var( exoid, 1, EX_FACE_BLOCK, 1, 500, 2, vals_face_var1fb1[0] ), "Unable to write face block 1 var 1.\n" ); EXCHECK( ex_put_var( exoid, 1, EX_FACE_BLOCK, 1, 700, 8, vals_face_var1fb3[0] ), "Unable to write face block 3 var 1.\n" ); EXCHECK( ex_put_var( exoid, 1, EX_ELEM_BLOCK, 1, 200, 2, vals_elem_var1eb1[0] ), "Unable to write elem block 1 var 1.\n" ); EXCHECK( ex_put_var( exoid, 1, EX_FACE_SET, 1, 1400, 2, vals_fset_var1fs1[0] ), "Unable to write face set 1 var 1.\n" ); t = 2.; EXCHECK( ex_put_time( exoid, 2, &t ), "Unable to write time value.\n" ); EXCHECK( ex_put_var( exoid, 2, EX_GLOBAL, 1, 0/*N/A*/, 2, vals_glo_var[1] ), "Unable to write global var 1.\n" ); EXCHECK( ex_put_var( exoid, 2, EX_EDGE_BLOCK, 1, 100, 20, vals_edge_var1eb1[1] ), "Unable to write edge block 1 var 1.\n" ); EXCHECK( ex_put_var( exoid, 2, EX_EDGE_BLOCK, 2, 100, 20, vals_edge_var2eb1[1] ), "Unable to write edge block 1 var 2.\n" ); EXCHECK( ex_put_var( exoid, 2, EX_FACE_BLOCK, 1, 500, 2, vals_face_var1fb1[1] ), "Unable to write face block 1 var 1.\n" ); EXCHECK( ex_put_var( exoid, 2, EX_FACE_BLOCK, 1, 700, 8, vals_face_var1fb3[1] ), "Unable to write face block 3 var 1.\n" ); EXCHECK( ex_put_var( exoid, 2, EX_ELEM_BLOCK, 1, 200, 2, vals_elem_var1eb1[1] ), "Unable to write elem block 1 var 1.\n" ); EXCHECK( ex_put_var( exoid, 2, EX_FACE_SET, 1, 1400, 2, vals_fset_var1fs1[1] ), "Unable to write face set 1 var 1.\n" ); EXCHECK( ex_put_nodal_var( exoid, 1, 1, 12, vals_nod_var[0] ), "Unable to write nodal var 1.\n" ); EXCHECK( ex_put_nodal_var( exoid, 2, 1, 12, vals_nod_var[1] ), "Unable to write nodal var 1.\n" ); EXCHECK( ex_close( exoid ), "Unable to close database.\n" ); return 0; } #ifndef EXO_CTEST int main( int argc, char* argv[] ) { return cCreateEdgeFace(argc, argv); } #endif /* EXO_CTEST */ xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expconn.c0000644000175000017500000002024611606020250022430 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* $Id: expconn.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ */ #include "exodusII.h" #include "exodusII_int.h" #include /* for free() */ /*! write out the connectivity array */ #define EX_WRITE_CONN(TNAME,VARCONN,VARCONNVAL) \ status = nc_put_var_int(exoid, VARCONN, VARCONNVAL); \ if (status != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to write connectivity array for %s block %d in file id %d", \ TNAME,blk_id,exoid); \ ex_err("ex_put_conn",errmsg, exerrval); \ return(EX_FATAL); \ } /*! * writes the connectivity array for a block * \param exoid exodus file id * \param blk_type type of block * \param blk_id id of block * \param node_conn node-element connectivity * \param elem_edge_conn element-edge connectivity (NULL if none) * \param elem_face_conn element-face connectivity (NULL if none) */ int ex_put_conn (int exoid, ex_entity_type blk_type, int blk_id, const int *node_conn, const int *elem_edge_conn, const int *elem_face_conn) { int connid=-1, blk_id_ndx, status; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ blk_id_ndx = ex_id_lkup(exoid,blk_type,blk_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: connectivity array not allowed for NULL %s block %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_conn",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate %s block id %d in id array in file id %d", ex_name_of_object(blk_type),blk_id, exoid); ex_err("ex_put_conn",errmsg,exerrval); return (EX_FATAL); } } /* inquire id's of previously defined dimensions */ switch (blk_type) { case EX_ELEM_BLOCK: status = nc_inq_varid (exoid, VAR_CONN(blk_id_ndx), &connid); break; case EX_FACE_BLOCK: status = nc_inq_varid (exoid, VAR_FBCONN(blk_id_ndx), &connid); break; case EX_EDGE_BLOCK: status = nc_inq_varid (exoid, VAR_EBCONN(blk_id_ndx), &connid); break; default: sprintf(errmsg, "Error: Called with invalid blk_type %d", blk_type ); ex_err("ex_put_conn",errmsg,exerrval); return (EX_FATAL); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate connectivity array for %s block %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_conn",errmsg, exerrval); return(EX_FATAL); } EX_WRITE_CONN(ex_name_of_object(blk_type),connid,node_conn); /* If there are edge and face connectivity arrays that belong with the element * block, write them now. Warn if they are required but not specified or * specified but not required. */ if ( blk_type == EX_ELEM_BLOCK ) { int nedpereldim, nfapereldim; size_t num_ed_per_elem, num_fa_per_elem; status = nc_inq_dimid (exoid, DIM_NUM_EDG_PER_EL(blk_id_ndx), &nedpereldim); if (status != NC_NOERR && elem_edge_conn != 0) { exerrval = status; sprintf(errmsg, "Error: edge connectivity specified but failed to " "locate number of edges/element in block %d in file id %d", blk_id,exoid); ex_err("ex_put_conn",errmsg,exerrval); return(EX_FATAL); } status = nc_inq_dimid (exoid, DIM_NUM_FAC_PER_EL(blk_id_ndx), &nfapereldim); if (status != NC_NOERR && elem_face_conn != 0) { exerrval = status; sprintf(errmsg, "Error: face connectivity specified but failed to " "locate number of faces/element in block %d in file id %d", blk_id,exoid); ex_err("ex_put_conn",errmsg,exerrval); return(EX_FATAL); } num_ed_per_elem = 0; if ((elem_edge_conn != 0) && (status = nc_inq_dimlen(exoid, nedpereldim, &num_ed_per_elem) != NC_NOERR)) { exerrval = status; sprintf(errmsg, "Error: failed to get number of edges/elem in block %d in file id %d", blk_id,exoid); ex_err("ex_put_conn",errmsg,exerrval); return(EX_FATAL); } num_fa_per_elem = 0; if ((elem_face_conn != 0) && (status = nc_inq_dimlen(exoid, nfapereldim, &num_fa_per_elem) != NC_NOERR)) { exerrval = status; sprintf(errmsg, "Error: failed to get number of faces/elem in block %d in file id %d", blk_id,exoid); ex_err("ex_put_conn",errmsg,exerrval); return(EX_FATAL); } if ( (num_ed_per_elem == 0 && elem_edge_conn != 0) || (num_ed_per_elem != 0 && elem_edge_conn == 0) ) { exerrval = (EX_FATAL); sprintf(errmsg, "Error: number of edges per element (%ld) doesn't " "agree with elem_edge_conn (0x%p)", (long)num_ed_per_elem, (void*)elem_edge_conn ); ex_err("ex_put_conn",errmsg,exerrval); return (EX_FATAL); } if ( (num_fa_per_elem == 0 && elem_face_conn != 0) || (num_fa_per_elem != 0 && elem_face_conn == 0) ) { exerrval = (EX_FATAL); sprintf(errmsg, "Error: number of faces per element (%ld) doesn't " "agree with elem_face_conn (0x%p)", (long)num_fa_per_elem, (void*)elem_face_conn ); ex_err("ex_put_conn",errmsg,exerrval); return (EX_FATAL); } if ( num_ed_per_elem != 0 ) { status = nc_inq_varid(exoid, VAR_ECONN(blk_id_ndx), &connid); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate connectivity array for " "element edge block %d in file id %d", blk_id,exoid); ex_err("ex_put_conn",errmsg, exerrval); return(EX_FATAL); } EX_WRITE_CONN("element edge",connid,elem_edge_conn); } if ( num_fa_per_elem != 0 ) { status = nc_inq_varid (exoid, VAR_FCONN(blk_id_ndx), &connid); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate connectivity array for " "element face block %d in file id %d", blk_id,exoid); ex_err("ex_put_conn",errmsg, exerrval); return(EX_FATAL); } EX_WRITE_CONN("element face",connid,elem_face_conn); } } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnams.c0000644000175000017500000001421211606020250022414 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnam - ex_get_names * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type, * * exit conditions - * char* names[] ptr array of names * * revision history - * * $Id: exgnams.c,v 1.1 2010-01-06 16:33:13 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the entity names from the database */ int ex_get_names (int exoid, ex_entity_type obj_type, char **names) { int status; size_t i; int j, varid, temp; size_t num_entity; size_t start[2]; char *ptr; char errmsg[MAX_ERR_LENGTH]; const char *routine = "ex_get_names"; exerrval = 0; /* clear error code */ /* inquire previously defined dimensions and variables */ switch (obj_type) { /* ======== BLOCKS ========= */ case EX_EDGE_BLOCK: ex_get_dimension(exoid, DIM_NUM_ED_BLK, "edge block", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_ED_BLK, &varid); break; case EX_FACE_BLOCK: ex_get_dimension(exoid, DIM_NUM_FA_BLK, "face block", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_FA_BLK, &varid); break; case EX_ELEM_BLOCK: ex_get_dimension(exoid, DIM_NUM_EL_BLK, "element block", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_EL_BLK, &varid); break; /* ======== SETS ========= */ case EX_NODE_SET: ex_get_dimension(exoid, DIM_NUM_NS, "nodeset", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_NS, &varid); break; case EX_EDGE_SET: ex_get_dimension(exoid, DIM_NUM_ES, "edgeset", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_ES, &varid); break; case EX_FACE_SET: ex_get_dimension(exoid, DIM_NUM_FS, "faceset", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_FS, &varid); break; case EX_SIDE_SET: ex_get_dimension(exoid, DIM_NUM_SS, "sideset", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_SS, &varid); break; case EX_ELEM_SET: ex_get_dimension(exoid, DIM_NUM_ELS, "elemset", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_ELS, &varid); break; /* ======== MAPS ========= */ case EX_NODE_MAP: ex_get_dimension(exoid, DIM_NUM_NM, "node map", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_NM, &varid); break; case EX_EDGE_MAP: ex_get_dimension(exoid, DIM_NUM_EDM, "edge map", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_EDM, &varid); break; case EX_FACE_MAP: ex_get_dimension(exoid, DIM_NUM_FAM, "face map", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_FAM, &varid); break; case EX_ELEM_MAP: ex_get_dimension(exoid, DIM_NUM_EM, "element map", &num_entity, &temp, routine); status = nc_inq_varid(exoid, VAR_NAME_EM, &varid); break; /* invalid variable type */ default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid type specified in file id %d", exoid); ex_err(routine,errmsg,exerrval); return(EX_FATAL); } if (status == NC_NOERR) { /* read the names */ for (i=0; i names[i]) { while (--ptr >= names[i] && *ptr == ' '); /* get rid of trailing blanks */ } *(++ptr) = '\0'; } } else { /* Names variable does not exist on the database; probably since this is an * older version of the database. Return an empty array... */ for (i=0; i /*! * writes an object property * \param exoid exodus file id * \param obj_type type of object * \param obj_id id of object to which property will be assigned * \param prop_name name of the property for which the value will be stored * \param value value of the property */ int ex_put_prop (int exoid, ex_entity_type obj_type, int obj_id, const char *prop_name, int value) { int status; int oldfill, temp; int found = FALSE; int num_props, i, dimid, propid, dims[1]; size_t start[1]; int ldum; char name[MAX_VAR_NAME_LENGTH+1]; char tmpstr[MAX_STR_LENGTH+1]; char dim_name[MAX_VAR_NAME_LENGTH+1]; int vals[1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* check if property has already been created */ num_props = ex_get_num_props(exoid, obj_type); if (num_props > 1) { /* any properties other than the default 1? */ for (i=1; i<=num_props; i++) { switch (obj_type) { case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(i)); break; case EX_EDGE_BLOCK: strcpy (name, VAR_ED_PROP(i)); break; case EX_FACE_BLOCK: strcpy (name, VAR_FA_PROP(i)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(i)); break; case EX_EDGE_SET: strcpy (name, VAR_ES_PROP(i)); break; case EX_FACE_SET: strcpy (name, VAR_FS_PROP(i)); break; case EX_ELEM_SET: strcpy (name, VAR_ELS_PROP(i)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(i)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(i)); break; case EX_FACE_MAP: strcpy (name, VAR_FAM_PROP(i)); break; case EX_EDGE_MAP: strcpy (name, VAR_EDM_PROP(i)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(i)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop",errmsg,exerrval); return(EX_FATAL); } if ((status = nc_inq_varid(exoid, name, &propid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get property array id in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } /* compare stored attribute name with passed property name */ memset(tmpstr, 0, MAX_STR_LENGTH+1); if ((status = nc_get_att_text(exoid, propid, ATT_PROP_NAME, tmpstr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get property name in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } if (strcmp(tmpstr, prop_name) == 0) { found = TRUE; break; } } } /* if property array has not been created, create it */ if (!found) { /* put netcdf file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } /* create a variable with a name xx_prop#, where # is the new number */ /* of the property */ switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_EL_BLK); break; case EX_FACE_BLOCK: strcpy (name, VAR_FA_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_FA_BLK); break; case EX_EDGE_BLOCK: strcpy (name, VAR_ED_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_ED_BLK); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_NS); break; case EX_EDGE_SET: strcpy (name, VAR_ES_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_ES); break; case EX_FACE_SET: strcpy (name, VAR_FS_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_FS); break; case EX_ELEM_SET: strcpy (name, VAR_ELS_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_ELS); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_SS); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_EM); break; case EX_FACE_MAP: strcpy (name, VAR_FAM_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_FAM); break; case EX_EDGE_MAP: strcpy (name, VAR_EDM_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_EDM); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_NM); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* inquire id of previously defined dimension (number of objects) */ if ((status = nc_inq_dimid(exoid, dim_name, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of objects in file id %d", exoid); ex_err("ex_put_prop",errmsg, exerrval); goto error_ret; /* Exit define mode and return */ } dims[0] = dimid; nc_set_fill(exoid, NC_FILL, &oldfill); /* fill with zeros per routine spec */ if ((status = nc_def_var(exoid, name, NC_INT, 1, dims, &propid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create property array variable in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } vals[0] = 0; /* fill value */ /* create attribute to cause variable to fill with zeros per routine spec */ if ((status = nc_put_att_int(exoid, propid, _FillValue, NC_INT, 1, vals)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create property name fill attribute in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* store property name as attribute of property array variable */ if ((status = nc_put_att_text(exoid, propid, ATT_PROP_NAME, strlen(prop_name)+1, (void*)prop_name)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store property name %s in file id %d", prop_name,exoid); ex_err("ex_put_prop",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to leave define mode in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } nc_set_fill(exoid, oldfill, &temp); /* default: nofill */ } /* find index into property array using obj_id; put value in property */ /* array at proper index; ex_id_lkup returns an index that is 1-based,*/ /* but netcdf expects 0-based arrays so subtract 1 */ /* special case: property name ID - check for duplicate ID assignment */ if (strcmp("ID",prop_name) == 0) { start[0] = ex_id_lkup (exoid, obj_type, value); if (exerrval != EX_LOOKUPFAIL) /* found the id */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Warning: attempt to assign duplicate %s ID %d in file id %d", ex_name_of_object(obj_type), value, exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_WARN); } } start[0] = ex_id_lkup (exoid, obj_type, obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no properties allowed for NULL %s id %d in file id %d", ex_name_of_object(obj_type), obj_id,exoid); ex_err("ex_put_prop",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to find value %d in %s property array in file id %d", obj_id, ex_name_of_object(obj_type), exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } } start[0] = start[0] - 1; ldum = (int)value; if ((status = nc_put_var1_int(exoid, propid, start, &ldum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store property value in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: nc_set_fill(exoid, oldfill, &temp); /* default: nofill */ if (nc_enddef (exoid) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expss.c0000755000175000017500000000602211606020250022117 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expss - ex_put_side_set * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * int* side_set_elem_list array of elements in side set * int* side_set_side_list array of sides in side set * exit conditions - * * revision history - * * $Id: expss.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the side set element list and side set side list for a single side set * \param exoid exodus file id * \param side_set_id side set id * \param *side_set_elem_list array of elements in side set * \param *side_set_side_list array of sides in side set * \deprecated Use ex_put_set()(exoid, EX_SIDE_SET, side_set_id, side_set_elem_list, side_set_side_list) */ int ex_put_side_set (int exoid, int side_set_id, const int *side_set_elem_list, const int *side_set_side_list) { return ex_put_set(exoid, EX_SIDE_SET, side_set_id, side_set_elem_list, side_set_side_list); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expset.c0000644000175000017500000001526311606020250022271 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expss - ex_put_set * * entry conditions - * input parameters: * int exoid exodus file id * int set_type set type * int set_id set id * int* set_entry_list array of entries in set * int* set_extra_list array of extras in set * exit conditions - * * revision history - * * $Id: expset.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /* for free() */ /*! * writes the set entry list and set extra list for a single set * \param exoid exodus file id * \param set_type set type * \param set_id set id * \param *set_entry_list array of entries in set * \param *set_extra_list array of extras in set */ int ex_put_set (int exoid, ex_entity_type set_type, int set_id, const int *set_entry_list, const int *set_extra_list) { int dimid, status; int entry_list_id, extra_list_id, set_id_ndx; char errmsg[MAX_ERR_LENGTH]; char* entryptr = NULL; char* extraptr = NULL; exerrval = 0; /* clear error code */ /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: no %ss defined in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_set",errmsg,exerrval); return (EX_FATAL); } /* Lookup index of set id in VAR_*S_IDS array */ set_id_ndx = ex_id_lkup(exoid, set_type,set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no data allowed for NULL %s %d in file id %d", ex_name_of_object(set_type),set_id,exoid); ex_err("ex_put_set",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate %s id %d in VAR_*S_IDS array in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set",errmsg,exerrval); return (EX_FATAL); } } /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { entryptr = VAR_NODE_NS(set_id_ndx); extraptr = NULL; } else if (set_type == EX_EDGE_SET) { entryptr = VAR_EDGE_ES(set_id_ndx); extraptr = VAR_ORNT_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { entryptr = VAR_FACE_FS(set_id_ndx); extraptr = VAR_ORNT_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { entryptr = VAR_ELEM_SS(set_id_ndx); extraptr = VAR_SIDE_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { entryptr = VAR_ELEM_ELS(set_id_ndx); extraptr = NULL; } /* inquire id's of previously defined variables */ if ((status = nc_inq_varid(exoid, entryptr, &entry_list_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate entry list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set",errmsg,exerrval); return (EX_FATAL); } /* only do for edge, face and side sets */ if (extraptr) { if ((status = nc_inq_varid(exoid, extraptr, &extra_list_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate extra list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set",errmsg,exerrval); return (EX_FATAL); } } /* write out the entry list and extra list arrays */ status = nc_put_var_int(exoid, entry_list_id, set_entry_list); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store entry list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set",errmsg,exerrval); return (EX_FATAL); } /* only do for edge, face and side sets */ if (extraptr) { if ( set_extra_list == NULL ) { sprintf(errmsg, "Error: extra list NULL for %s %d in file id %d", ex_name_of_object(set_type), set_id, exoid ); ex_err("ex_put_set",errmsg,EX_BADPARAM); return (EX_FATAL); } status = nc_put_var_int(exoid, extra_list_id, set_extra_list); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store extra list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_put_set",errmsg,exerrval); return (EX_FATAL); } } /* warn if extra data was sent in for node sets and elem sets */ if ((set_type == EX_NODE_SET || set_type == EX_ELEM_SET) && set_extra_list != NULL) { sprintf(errmsg, "Warning: extra list was ignored for %s %d in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_put_set",errmsg,EX_MSG); return(EX_WARN); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exginf.c0000755000175000017500000001045011606020250022235 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exginf - ex_get_info * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * char* info[] ptr array of info records * * revision history - * * $Id: exginf.c,v 1.1 2010-01-06 16:33:12 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads information records from the database */ int ex_get_info (int exoid, char **info) { int status; size_t i; int j, dimid, varid; size_t num_info, start[2]; char *ptr; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined dimensions and variables */ if ((status = nc_inq_dimid (exoid, DIM_NUM_INFO, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: failed to locate number of info records in file id %d", exoid); ex_err("ex_get_info",errmsg,exerrval); return (EX_WARN); } if ((status = nc_inq_dimlen(exoid, dimid, &num_info)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of info records in file id %d", exoid); ex_err("ex_get_info",errmsg,exerrval); return (EX_FATAL); } /* do this only if there are any information records */ if (num_info > 0) { if ((status = nc_inq_varid(exoid, VAR_INFO, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate info record data in file id %d", exoid); ex_err("ex_get_info",errmsg,exerrval); return (EX_FATAL); } /* read the information records */ for (i=0; i= info[i] && *ptr == ' ' ); *(++ptr) = '\0'; } } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnv.c0000755000175000017500000001067511606020250022115 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnv - ex_get_nodal_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step whole time step number * int nodeal_var_index index of desired nodal variable * int num_nodes number of nodal points * * exit conditions - * float* nodal_var_vals array of nodal variable values * * revision history - * * $Id: exgnv.c,v 1.1 2010-01-06 16:33:20 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the values of a single nodal variable for a single time step from * the database; assume the first time step and nodal variable index is 1 */ int ex_get_nodal_var (int exoid, int time_step, int nodal_var_index, int num_nodes, void *nodal_var_vals) { int varid; int status; size_t start[3], count[3]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined variable */ if (ex_large_model(exoid) == 0) { /* read values of the nodal variable */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variables in file id %d", exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --time_step; start[1] = --nodal_var_index; start[2] = 0; count[0] = 1; count[1] = 1; count[2] = num_nodes; } else { /* read values of the nodal variable -- stored as separate variables... */ /* Get the varid.... */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(nodal_var_index), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", nodal_var_index, exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_nodes; } if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, nodal_var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, nodal_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get nodal variables in file id %d", exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgoea.c0000644000175000017500000000524511606020250022230 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgeat - ex_get_one_elem_attr * * entry conditions - * input parameters: * int exoid exodus file id * int elem_blk_id element block id * * exit conditions - * float* attrib array of attributes * * revision history - * * $Id: exgoea.c,v 1.1 2010-01-06 16:33:30 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the attributes for an element block * \deprecated Use ex_get_one_attr()(exoid, EX_ELEM_BLOCK, elem_blk_id, attrib_index, attrib) */ int ex_get_one_elem_attr (int exoid, int elem_blk_id, int attrib_index, void *attrib) { return ex_get_one_attr( exoid, EX_ELEM_BLOCK, elem_blk_id, attrib_index, attrib ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgmap.c0000755000175000017500000000710011606020250022234 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgmap - ex_get_map * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int* elem_map element order map array * * revision history - * * $Id: exgmap.c,v 1.1 2010-01-06 16:33:12 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the element order map from the database * \deprecated Use ex_get_num_map() instead. */ int ex_get_map (int exoid, int *elem_map) { int numelemdim, mapid, status; size_t i, num_elem; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire id's of previously defined dimensions and variables */ /* See if file contains any elements...*/ if ((status = nc_inq_dimid (exoid, DIM_NUM_ELEM, &numelemdim)) != NC_NOERR) { return (EX_NOERR); } if ((status = nc_inq_dimlen(exoid, numelemdim, &num_elem)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of elements in file id %d", exoid); ex_err("ex_get_map",errmsg,exerrval); return (EX_FATAL); } if (nc_inq_varid(exoid, VAR_MAP, &mapid) != NC_NOERR) { /* generate default map of 1..n, where n is num_elem */ for (i=0; i #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the parameters used to describe an element block * \param exoid exodus file id * \param elem_blk_id element block id * \param elem_type element type string * \param num_elem_this_blk number of elements in the element blk * \param num_nodes_per_elem number of nodes per element block * \param num_attr number of attributes * \param define_maps if != 0, write maps, else don't */ int ex_put_concat_elem_block (int exoid, const int* elem_blk_id, char *elem_type[], const int* num_elem_this_blk, const int* num_nodes_per_elem, const int* num_attr, int define_maps) { int i, varid, dimid, dims[2], strdim, *eb_stat; int temp; int iblk; int status; int num_elem_blk; size_t length; int cur_num_elem_blk, nelnoddim, numelbdim, numattrdim, connid, numelemdim, numnodedim; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* first check if any element blocks are specified * OK if zero... */ if (nc_inq_dimid(exoid, DIM_NUM_EL_BLK, &dimid) != NC_NOERR) { return (EX_NOERR); } /* Get number of element blocks defined for this file */ if ((status = nc_inq_dimlen(exoid,dimid,&length)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of element blocks in file id %d", exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); return (EX_FATAL); } num_elem_blk = length; /* Fill out the element block status array */ if (!(eb_stat = malloc(num_elem_blk*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for element block status array in file id %d", exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); return (EX_FATAL); } for (i=0;i= num_elem_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of element blocks (%d) defined in file id %d", num_elem_blk,exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; } /* NOTE: ex_inc_file_item is used to find the number of element blocks for a specific file and returns that value incremented. */ cur_num_elem_blk=ex_inc_file_item(exoid, ex_get_counter_list(EX_ELEM_BLOCK)); if (num_elem_this_blk[iblk] == 0) /* Is this a NULL element block? */ continue; /* define some dimensions and variables*/ if ((status = nc_def_dim(exoid, DIM_NUM_EL_IN_BLK(cur_num_elem_blk+1), num_elem_this_blk[iblk], &numelbdim)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { /* duplicate entry */ sprintf(errmsg, "Error: element block %d already defined in file id %d", elem_blk_id[iblk],exoid); } else { sprintf(errmsg, "Error: failed to define number of elements/block for block %d file id %d", elem_blk_id[iblk],exoid); } ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ((status = nc_def_dim(exoid, DIM_NUM_NOD_PER_EL(cur_num_elem_blk+1), num_nodes_per_elem[iblk], &nelnoddim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of nodes/element for block %d in file id %d", elem_blk_id[iblk],exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* element connectivity array */ dims[0] = numelbdim; dims[1] = nelnoddim; if ((status = nc_def_var (exoid, VAR_CONN(cur_num_elem_blk+1), NC_INT, 2, dims, &connid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create connectivity array for block %d in file id %d", elem_blk_id[iblk],exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store element type as attribute of connectivity variable */ if ((status = nc_put_att_text(exoid, connid, ATT_NAME_ELB, strlen(elem_type[iblk])+1, (void*)elem_type[iblk])) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store element type name %s in file id %d", elem_type[iblk],exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* element attribute array */ if (num_attr[iblk] > 0) { if ((status = nc_def_dim (exoid, DIM_NUM_ATT_IN_BLK(cur_num_elem_blk+1), num_attr[iblk], &numattrdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of attributes in block %d in file id %d", elem_blk_id[iblk],exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* Attribute names... */ dims[0] = numattrdim; dims[1] = strdim; if ((status = nc_def_var(exoid, VAR_NAME_ATTRIB(cur_num_elem_blk+1), NC_CHAR, 2, dims, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define element attribute name array in file id %d",exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } dims[0] = numelbdim; dims[1] = numattrdim; if ((status = nc_def_var(exoid, VAR_ATTRIB(cur_num_elem_blk+1), nc_flt_code(exoid), 2, dims, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define attributes for element block %d in file id %d", elem_blk_id[iblk],exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } /* Define the element map here to avoid a later redefine call */ if (define_maps != 0) { if (nc_inq_varid(exoid, VAR_ELEM_NUM_MAP, &temp) != NC_NOERR) { /* Map does not exist */ /* Possible to have zero elements but >0 element blocks. * Only define map if there are nonzero elements */ if (nc_inq_dimid(exoid, DIM_NUM_ELEM, &numelemdim) == NC_NOERR) { dims[0] = numelemdim; if ((status = nc_def_var(exoid, VAR_ELEM_NUM_MAP, NC_INT, 1, dims, &temp)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { sprintf(errmsg, "Error: element numbering map already exists in file id %d", exoid); } else { sprintf(errmsg, "Error: failed to create element numbering map in file id %d", exoid); } ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } /* Do the same for the node numbering map */ if (nc_inq_varid(exoid, VAR_NODE_NUM_MAP, &temp) != NC_NOERR) { /* Map does not exist */ if ((nc_inq_dimid(exoid, DIM_NUM_NODES, &numnodedim)) == NC_NOERR) { dims[0] = numnodedim; if ((status = nc_def_var(exoid, VAR_NODE_NUM_MAP, NC_INT, 1, dims, &temp)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { sprintf(errmsg, "Error: node numbering map already exists in file id %d", exoid); } else { sprintf(errmsg, "Error: failed to create node numbering map array in file id %d", exoid); } ex_err("ex_put_concat_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } } /* leave define mode */ if ((status = nc_enddef(exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete element block definition in file id %d", exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_concat_elem_block",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnstt.c0000644000175000017500000000701011606020250022455 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnstt - ex_put_nset_var_tab * * entry conditions - * input parameters: * int exoid exodus file id * int num_nset number of nodesets * int num_nset_var number of nodeset variables * int* nset_var_tab nodeset variable truth table array * * exit conditions - * * $Id: expnstt.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the EXODUS II nodeset variable truth table to the database; * also, creates netCDF variables in which to store EXODUS II nodeset * variable values; although this table isn't required (because the * netCDF variables can also be created in ex_put_nset_var), this call * will save tremendous time because all of the variables are defined * at once while the file is in define mode, rather than going in and out * of define mode (causing the entire file to be copied over and over) * which is what occurs when the nodeset variable values variables are * defined in ex_put_nset_var * \param exoid exodus file id * \param num_nset number of nodesets * \param num_nset_var number of nodeset variables * \param nset_var_tab nodeset variable truth table array * \deprecated Use ex_put_truth_table()(exoid, EX_NODE_SET, num_nset, num_nset_var, nset_var_tab) */ int ex_put_nset_var_tab (int exoid, int num_nset, int num_nset_var, int *nset_var_tab) { return ex_put_truth_table(exoid, EX_NODE_SET, num_nset, num_nset_var, nset_var_tab); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnm.c0000755000175000017500000000477411606020250022107 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnm - ex_get_node_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_id node map id * * exit conditions - * int* node_map node map * * revision history - * * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the node map with specified ID * \deprecated Use ex_get_num_map()(exoid, EX_NODE_MAP, map_id, node_map */ int ex_get_node_map( int exoid, int map_id, int *node_map ) { return ex_get_num_map( exoid, EX_NODE_MAP, map_id, node_map ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgset.c0000644000175000017500000001434711606020250022262 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgset - ex_get_set * * entry conditions - * input parameters: * int exoid exodus file id * int set_type the type of set * int set_id set id * * exit conditions - * int* set_entry_list array of entries in set * int* set_extra_list array of extras in set * * revision history - * * $Id: exgset.c,v 1.1 2010-01-06 16:33:33 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the set entry list and set extra list for a single set */ int ex_get_set (int exoid, ex_entity_type set_type, int set_id, int *set_entry_list, int *set_extra_list) /* NULL if dont want to retrieve data */ { int dimid, entry_list_id, extra_list_id, status; int set_id_ndx; char errmsg[MAX_ERR_LENGTH]; char* numentryptr; char* entryptr = NULL; char* extraptr = NULL; exerrval = 0; /* clear error code */ /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no %ss stored in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_get_set",errmsg,exerrval); return (EX_WARN); } /* Lookup index of set id in VAR_*S_IDS array */ set_id_ndx = ex_id_lkup(exoid,set_type,set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: %s %d is NULL in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate %s id %d in VAR_*S_IDS array in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set",errmsg,exerrval); return (EX_FATAL); } } /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { numentryptr = DIM_NUM_NOD_NS(set_id_ndx); entryptr = VAR_NODE_NS(set_id_ndx); extraptr = NULL; } else if (set_type == EX_EDGE_SET) { numentryptr = DIM_NUM_EDGE_ES(set_id_ndx); entryptr = VAR_EDGE_ES(set_id_ndx); extraptr = VAR_ORNT_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { numentryptr = DIM_NUM_FACE_FS(set_id_ndx); entryptr = VAR_FACE_FS(set_id_ndx); extraptr = VAR_ORNT_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { numentryptr = DIM_NUM_SIDE_SS(set_id_ndx); entryptr = VAR_ELEM_SS(set_id_ndx); extraptr = VAR_SIDE_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { numentryptr = DIM_NUM_ELE_ELS(set_id_ndx); entryptr = VAR_ELEM_ELS(set_id_ndx); extraptr = NULL; } /* inquire id's of previously defined dimensions and variables */ if ((status = nc_inq_varid(exoid, entryptr, &entry_list_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate entry list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set",errmsg,exerrval); return (EX_FATAL); } /* If client doet not pass in an array to store the extra list, don't access it at all */ if (set_extra_list == NULL) extraptr = NULL; /* only do extra list for edge, face and side sets */ if (extraptr) { if ((status = nc_inq_varid (exoid, extraptr, &extra_list_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate extra list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set",errmsg,exerrval); return (EX_FATAL); } } /* read in the entry list and extra list arrays */ status = nc_get_var_int(exoid, entry_list_id, set_entry_list); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get entry list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set",errmsg,exerrval); return (EX_FATAL); } /* only do extra list for edge, face and side sets */ if (extraptr) { status = nc_get_var_int(exoid, extra_list_id, set_extra_list); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get extra list for %s %d in file id %d", ex_name_of_object(set_type), set_id,exoid); ex_err("ex_get_set",errmsg,exerrval); return (EX_FATAL); } } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exggv.c0000755000175000017500000000730211606020250022077 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exggv - ex_get_glob_vars * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int num_glob_vars number of global vars in file * * exit conditions - * float* glob_var_vals array of global variable values * * revision history - * * $Id: exggv.c,v 1.1 2010-01-06 16:33:11 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the values of all the global variables for a single time step from * the database; time step numbers are assumed to start at 1 */ int ex_get_glob_vars (int exoid, int time_step, int num_glob_vars, void *glob_var_vals) { int varid; int status; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined variable */ if ((status = nc_inq_varid (exoid, VAR_GLO_VAR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: failed to locate global variables in file id %d", exoid); ex_err("ex_get_glob_vars",errmsg,exerrval); return (EX_WARN); } /* read values of global variables */ start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_glob_vars; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, glob_var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, glob_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get global variable values from file id %d", exoid); ex_err("ex_get_glob_vars",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgev.c0000755000175000017500000000621311606020250022075 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgev - ex_get_elem_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int elem_var_index element variable index * int elem_blk_id element block id * int num_elem_this_blk number of elements in this block * * * exit conditions - * float* elem_var_vals array of element variable values * * * revision history - * * $Id: exgev.c,v 1.1 2010-01-06 16:33:07 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the values of a single element variable for one element block at * one time step in the database; assume the first time step and * element variable index is 1 * \deprecated Use ex_get_var()(exoid, time_step, EX_ELEM_BLOCK, elem_var_index, elem_blk_id, num_elem_this_blk, elem_var_vals) instead */ int ex_get_elem_var (int exoid, int time_step, int elem_var_index, int elem_blk_id, int num_elem_this_blk, void *elem_var_vals) { return ex_get_var( exoid, time_step, EX_ELEM_BLOCK, elem_var_index, elem_blk_id, num_elem_this_blk, elem_var_vals ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnvid.c0000755000175000017500000001013411606020250022420 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnvid - ex_get_nodal_varid * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int* varid array of nodal variable varids * * revision history - * * $Id: exgnvid.c,v 1.1 2010-01-06 16:33:23 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * returns the varids for the nodal variables. */ int ex_get_nodal_varid(int exoid, int *varid) { int status; int dimid, nvarid; size_t i, num_vars; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ if ((status = nc_inq_dimid(exoid, DIM_NUM_NOD_VAR, &dimid)) != NC_NOERR) { num_vars = 0; if (status == NC_EBADDIM) return(EX_NOERR); /* no nodal variables defined */ else { exerrval = status; sprintf(errmsg, "Error: failed to locate nodal variable names in file id %d", exoid); ex_err("ex_get_nodal_varid",errmsg,exerrval); return (EX_FATAL); } } if ((status = nc_inq_dimlen(exoid, dimid, &num_vars)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of nodal variables in file id %d", exoid); ex_err("ex_get_nodal_varid",errmsg,exerrval); return (EX_FATAL); } if (ex_large_model(exoid) == 0) { /* All varids are the same; */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &nvarid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variables in file id %d", exoid); ex_err("ex_get_nodal_varid",errmsg,exerrval); return (EX_WARN); } for (i=0; i < num_vars; i++) { varid[i] = nvarid; } } else { /* Variables stored separately; each has a unique varid */ for (i=0; i < num_vars; i++) { if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(i+1), &nvarid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", (int)i+1, exoid); ex_err("ex_get_nodal_varid",errmsg,exerrval); return (EX_WARN); } varid[i] = nvarid; } } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvarparam.c0000644000175000017500000002707611606020250023314 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvp - ex_put_var_param * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type * int* num_vars number of variables in database * * exit conditions - * * revision history - * * $Id: expvarparam.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include #define EX_PREPARE_RESULT_VAR(TNAME,DIMNAME,VARNAMEVAR) \ if ((status = nc_def_dim(exoid, DIMNAME, num_vars, &dimid)) != NC_NOERR) { \ if (status == NC_ENAMEINUSE) { \ exerrval = status; \ sprintf(errmsg, \ "Error: " TNAME " variable name parameters are already defined in file id %d", \ exoid); \ ex_err("ex_put_var_param",errmsg,exerrval); \ } else { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define number of " TNAME " variables in file id %d", \ exoid); \ ex_err("ex_put_var_param",errmsg,exerrval); \ } \ goto error_ret; /* exit define mode and return */ \ } \ /* Now define TNAME variable name variable */ \ dims[0] = dimid; \ dims[1] = strdim; \ if ((status = nc_def_var (exoid, VARNAMEVAR, NC_CHAR, 2, dims, &varid)) != NC_NOERR) { \ if (status == NC_ENAMEINUSE) { \ exerrval = status; \ sprintf(errmsg, \ "Error: " TNAME " variable names are already defined in file id %d", \ exoid); \ ex_err("ex_put_variable_param",errmsg,exerrval); \ } else { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define " TNAME " variable names in file id %d", \ exoid); \ ex_err("ex_put_variable_param",errmsg,exerrval); \ } \ goto error_ret; /* exit define mode and return */ \ } /*! * writes the number and names of global, nodal, or element variables * that will be written to the database * \param exoid exodus file id * \param obj_type object type * \param *num_vars number of variables in database */ int ex_put_variable_param (int exoid, ex_entity_type obj_type, int num_vars) { int time_dim, num_nod_dim, dimid, strdim, varid; int dims[3]; char errmsg[MAX_ERR_LENGTH]; int status; exerrval = 0; /* clear error code */ /* if no variables are to be stored, return with warning */ if (num_vars == 0) { exerrval = EX_MSG; sprintf(errmsg, "Warning: zero %s variables specified for file id %d", ex_name_of_object(obj_type),exoid); ex_err("ex_put_variable_param",errmsg,exerrval); return (EX_WARN); } if ( obj_type != EX_NODAL && obj_type != EX_NODE_SET && obj_type != EX_EDGE_BLOCK && obj_type != EX_EDGE_SET && obj_type != EX_FACE_BLOCK && obj_type != EX_FACE_SET && obj_type != EX_ELEM_BLOCK && obj_type != EX_ELEM_SET && obj_type != EX_SIDE_SET && obj_type != EX_GLOBAL) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid variable type %d specified in file id %d", obj_type, exoid); ex_err("ex_put_variable_param",errmsg,exerrval); return (EX_WARN); } /* inquire previously defined dimensions */ if ((status = nc_inq_dimid (exoid, DIM_TIME, &time_dim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate time dimension in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_dimid (exoid, DIM_NUM_NODES, &num_nod_dim)) != NC_NOERR) { if (obj_type == EX_NODAL) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of nodes in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); return (EX_FATAL); } } if ((status = nc_inq_dimid (exoid, DIM_STR, &strdim)) < 0) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_variable_param",errmsg,exerrval); return (EX_FATAL); } /* put file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_get_var_param",errmsg,exerrval); return (EX_FATAL); } /* define dimensions and variables */ if (obj_type == EX_GLOBAL) { EX_PREPARE_RESULT_VAR("global",DIM_NUM_GLO_VAR,VAR_NAME_GLO_VAR); dims[0] = time_dim; dims[1] = dimid; if ((status = nc_def_var (exoid, VAR_GLO_VAR, nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define global variables in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } else if (obj_type == EX_NODAL) { /* * There are two ways to store the nodal variables. The old way * * was a blob (#times,#vars,#nodes), but that was exceeding the * netcdf maximum dataset size for large models. The new way is * to store #vars separate datasets each of size (#times,#nodes) * * We want this routine to be capable of storing both formats * based on some external flag. Since the storage format of the * coordinates have also been changed, we key off of their * storage type to decide which method to use for nodal * variables. If the variable 'coord' is defined, then store old * way; otherwise store new. */ if ((status = nc_def_dim(exoid, DIM_NUM_NOD_VAR, num_vars, &dimid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: nodal variable name parameters are already defined in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define number of nodal variables in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } if (ex_large_model(exoid) == 0) { /* Old way */ dims[0] = time_dim; dims[1] = dimid; dims[2] = num_nod_dim; if ((status = nc_def_var(exoid, VAR_NOD_VAR, nc_flt_code(exoid), 3, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define nodal variables in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } else { /* New way */ int i; for (i = 1; i <= num_vars; i++) { dims[0] = time_dim; dims[1] = num_nod_dim; if ((status = nc_def_var (exoid, VAR_NOD_VAR_NEW(i), nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define nodal variable %d in file id %d", i, exoid); ex_err("ex_put_variable_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } /* Now define nodal variable name variable */ dims[0] = dimid; dims[1] = strdim; if ((status = nc_def_var(exoid, VAR_NAME_NOD_VAR, NC_CHAR, 2, dims, &varid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: nodal variable names are already defined in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define nodal variable names in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } } /* netCDF variables in which to store the EXODUS obj_type variable values will * be defined in ex_put_*_var_tab or ex_put_*_var; at this point, we * don't know what obj_type variables are valid for which obj_type blocks * (the info that is stored in the obj_type variable truth table) */ else if (obj_type == EX_ELEM_BLOCK) { EX_PREPARE_RESULT_VAR("element",DIM_NUM_ELE_VAR,VAR_NAME_ELE_VAR); } else if (obj_type == EX_NODE_SET) { EX_PREPARE_RESULT_VAR("nodeset",DIM_NUM_NSET_VAR,VAR_NAME_NSET_VAR); } else if (obj_type == EX_SIDE_SET) { EX_PREPARE_RESULT_VAR("sideset",DIM_NUM_SSET_VAR,VAR_NAME_SSET_VAR); } else if (obj_type == EX_EDGE_BLOCK) { EX_PREPARE_RESULT_VAR("edge",DIM_NUM_EDG_VAR,VAR_NAME_EDG_VAR); } else if (obj_type == EX_FACE_BLOCK) { EX_PREPARE_RESULT_VAR("face",DIM_NUM_FAC_VAR,VAR_NAME_FAC_VAR); } else if (obj_type == EX_EDGE_SET) { EX_PREPARE_RESULT_VAR("edgeset",DIM_NUM_ESET_VAR,VAR_NAME_ESET_VAR); } else if (obj_type == EX_FACE_SET) { EX_PREPARE_RESULT_VAR("faceset",DIM_NUM_FSET_VAR,VAR_NAME_FSET_VAR); } else if (obj_type == EX_ELEM_SET) { EX_PREPARE_RESULT_VAR("elementset",DIM_NUM_ELSET_VAR,VAR_NAME_ELSET_VAR); } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete definition in file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if ((status = nc_enddef(exoid)) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_variable_param",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgqa.c0000755000175000017500000001050711606020250022065 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgqa - ex_get_qa * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * char* qa_record[8][4] ptr to qa record ptr array * * revision history - * * $Id: exgqa.c,v 1.1 2010-01-06 16:33:32 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the QA records from the database */ int ex_get_qa (int exoid, char *qa_record[][4]) { int status; int i, j, k, dimid, varid; size_t num_qa_records, start[3]; char *ptr; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined dimensions and variables */ if ((status = nc_inq_dimid(exoid, DIM_NUM_QA, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no qa records stored in file id %d", exoid); ex_err("ex_get_qa",errmsg,exerrval); return (EX_WARN); } if ((status = nc_inq_dimlen(exoid, dimid, &num_qa_records)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of qa records in file id %d", exoid); ex_err("ex_get_qa",errmsg,exerrval); return (EX_FATAL); } /* do this only if there are any QA records */ if (num_qa_records > 0) { if ((status = nc_inq_varid(exoid, VAR_QA_TITLE, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate qa record data in file id %d", exoid); ex_err("ex_get_qa",errmsg,exerrval); return (EX_FATAL); } /* read the QA records */ for (i=0; i<(int)num_qa_records; i++) { for (j=0; j<4; j++) { start[0] = i; start[1] = j; start[2] = 0; k = 0; ptr = qa_record[i][j]; if ((status = nc_get_var1_text(exoid, varid, start, ptr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get qa record data in file id %d", exoid); ex_err("ex_get_qa",errmsg,exerrval); return (EX_FATAL); } while ((*(ptr++) != '\0') && (k < MAX_STR_LENGTH)) { start[2] = ++k; if ((status = nc_get_var1_text(exoid, varid, start, ptr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get qa record data in file id %d", exoid); ex_err("ex_get_qa",errmsg,exerrval); return (EX_FATAL); } } /* remove trailing blanks */ if(start[2] != 0) { --ptr; while ( --ptr >= qa_record[i][j] && *ptr == ' ' ); *(++ptr) = '\0'; } } } } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgssi.c0000755000175000017500000000470111606020250022261 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgssi - ex_get_side_set_ids * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int* size_set_ids array of side set IDs * * revision history - * * $Id: exgssi.c,v 1.1 2010-01-06 16:33:37 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the side set ids from the database * \deprecated Use ex_get_ids()(exoid, EX_SIDE_SET, ids) */ int ex_get_side_set_ids (int exoid, int *ids) { return ex_get_ids( exoid, EX_SIDE_SET, ids ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgpa.c0000755000175000017500000001353311606020250022066 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgpa - ex_get_prop_array: read object property array * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type type of object (element block, node * set or side set) * char* prop_name name of the property for which the * values will be read * * exit conditions - * int* values returned array of property values * * revision history - * * $Id: exgpa.c,v 1.1 2010-01-06 16:33:32 kwleiter Exp $ * *****************************************************************************/ #include #include #include "exodusII.h" #include "exodusII_int.h" /* * reads an array of object properties */ int ex_get_prop_array (int exoid, ex_entity_type obj_type, const char *prop_name, int *values) { int num_props, i, propid, status; int found = FALSE; char name[MAX_VAR_NAME_LENGTH+1]; char tmpstr[MAX_STR_LENGTH+1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* open appropriate variable, depending on obj_type and prop_name */ num_props = ex_get_num_props(exoid, obj_type); for (i=1; i<=num_props; i++) { switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(i)); break; case EX_EDGE_BLOCK: strcpy (name, VAR_ED_PROP(i)); break; case EX_FACE_BLOCK: strcpy (name, VAR_FA_PROP(i)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(i)); break; case EX_EDGE_SET: strcpy (name, VAR_ES_PROP(i)); break; case EX_FACE_SET: strcpy (name, VAR_FS_PROP(i)); break; case EX_ELEM_SET: strcpy (name, VAR_ELS_PROP(i)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(i)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(i)); break; case EX_FACE_MAP: strcpy (name, VAR_FAM_PROP(i)); break; case EX_EDGE_MAP: strcpy (name, VAR_EDM_PROP(i)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(i)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_get_prop_array",errmsg,exerrval); return(EX_FATAL); } if ((status = nc_inq_varid(exoid, name, &propid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate property array %s in file id %d", name, exoid); ex_err("ex_get_prop_array",errmsg,exerrval); return (EX_FATAL); } /* compare stored attribute name with passed property name */ memset(tmpstr, 0, MAX_STR_LENGTH+1); if ((status = nc_get_att_text(exoid, propid, ATT_PROP_NAME, tmpstr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get property name in file id %d", exoid); ex_err("ex_get_prop_array",errmsg,exerrval); return (EX_FATAL); } if (strcmp(tmpstr, prop_name) == 0) { found = TRUE; break; } } /* if property is not found, return warning */ if (!found) { exerrval = EX_BADPARAM; sprintf(errmsg, "Warning: object type %d, property %s not defined in file id %d", obj_type, prop_name, exoid); ex_err("ex_get_prop_array",errmsg,exerrval); return (EX_WARN); } /* read num_obj values from property variable */ status = nc_get_var_int(exoid, propid, values); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to read values in %s property array in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_get_prop_array",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expattp.c0000644000175000017500000002053011606020250022437 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expmp - ex_put_attr_param * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type block/set type (node, edge, face, elem) * int obj_id block/set id (ignored for NODAL) * int num_attrs number of attributes * * exit conditions - * * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * defines the number of attributes. * \param exoid exodus file id * \param obj_type block/set type (node, edge, face, elem) * \param obj_id block/set id (ignored for NODAL) * \param num_attrs number of attributes */ int ex_put_attr_param (int exoid, ex_entity_type obj_type, int obj_id, int num_attrs) { int status; int dims[2]; int strdim, varid; char errmsg[MAX_ERR_LENGTH]; const char *dnumobjent; const char *dnumobjatt; const char *vobjatt; const char *vattnam; int numobjentdim; int obj_id_ndx; int numattrdim; /* Determine index of obj_id in obj_type id array */ if (obj_type == EX_NODAL) obj_id_ndx = 0; else { obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes found for NULL %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_put_attr_param",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this object */ } else { sprintf(errmsg, "Warning: failed to locate %s id %d in id array in file id %d", ex_name_of_object(obj_type),obj_id, exoid); ex_err("ex_put_attr_param",errmsg,exerrval); return (EX_WARN); } } } switch (obj_type) { case EX_SIDE_SET: dnumobjent = DIM_NUM_SIDE_SS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx); vobjatt = VAR_SSATTRIB(obj_id_ndx); vattnam = VAR_NAME_SSATTRIB(obj_id_ndx); break; case EX_NODE_SET: dnumobjent = DIM_NUM_NOD_NS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx); vobjatt = VAR_NSATTRIB(obj_id_ndx); vattnam = VAR_NAME_NSATTRIB(obj_id_ndx); break; case EX_EDGE_SET: dnumobjent = DIM_NUM_EDGE_ES(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx); vobjatt = VAR_ESATTRIB(obj_id_ndx); vattnam = VAR_NAME_ESATTRIB(obj_id_ndx); break; case EX_FACE_SET: dnumobjent = DIM_NUM_FACE_FS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx); vobjatt = VAR_FSATTRIB(obj_id_ndx); vattnam = VAR_NAME_FSATTRIB(obj_id_ndx); break; case EX_ELEM_SET: dnumobjent = DIM_NUM_ELE_ELS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx); vobjatt = VAR_ELSATTRIB(obj_id_ndx); vattnam = VAR_NAME_ELSATTRIB(obj_id_ndx); break; case EX_NODAL: dnumobjent = DIM_NUM_NODES; dnumobjatt = DIM_NUM_ATT_IN_NBLK; vobjatt = VAR_NATTRIB; vattnam = VAR_NAME_NATTRIB; break; case EX_EDGE_BLOCK: dnumobjent = DIM_NUM_ED_IN_EBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx); vobjatt = VAR_EATTRIB(obj_id_ndx); vattnam = VAR_NAME_EATTRIB(obj_id_ndx); break; case EX_FACE_BLOCK: dnumobjent = DIM_NUM_FA_IN_FBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx); vobjatt = VAR_FATTRIB(obj_id_ndx); vattnam = VAR_NAME_FATTRIB(obj_id_ndx); break; case EX_ELEM_BLOCK: dnumobjent = DIM_NUM_EL_IN_BLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx); vobjatt = VAR_ATTRIB(obj_id_ndx); vattnam = VAR_NAME_ATTRIB(obj_id_ndx); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Bad block type (%d) specified for file id %d", obj_type, exoid ); ex_err("ex_put_attr_param",errmsg,exerrval); return (EX_FATAL); } exerrval = 0; /* clear error code */ if ((status = nc_inq_dimid(exoid, dnumobjent, &numobjentdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of entries for %s %d in file id %d", ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_put_attr_param",errmsg,exerrval); return (EX_FATAL); } /* put netcdf file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_attr_param",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_def_dim(exoid, dnumobjatt, num_attrs, &numattrdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of attributes in %s %d in file id %d", ex_name_of_object(obj_type), obj_id,exoid); ex_err("ex_put_attr_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } dims[0] = numobjentdim; dims[1] = numattrdim; if ((status = nc_def_var(exoid, vobjatt, nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define attributes for %s %d in file id %d", ex_name_of_object(obj_type), obj_id,exoid); ex_err("ex_put_attr_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_STR, &strdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_attr_param",errmsg,exerrval); return (EX_FATAL); } /* Attribute names... */ dims[0] = numattrdim; dims[1] = strdim; if ((status = nc_def_var(exoid, vattnam, NC_CHAR, 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define %s attribute name array in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_put_attr_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef(exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete %s attribute parameter definition in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_put_attr_param",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_attr_param",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgp.c0000755000175000017500000001540311606020250021723 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expp - ex_get_prop: read object property * * entry conditions - * input parameters: * int exoid exodus file id * ex_entity_type obj_type type of object (element block, node * set or side set) * int obj_id id of object for which value * is desired * char* prop_name name of the property for which * value is desired * * exit conditions - * int* value returned value of the property * * revision history - * * $Id: exgp.c,v 1.1 2010-01-06 16:33:31 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads an object property */ int ex_get_prop (int exoid, ex_entity_type obj_type, int obj_id, const char *prop_name, int *value) { int status; int num_props, i, propid; int found = FALSE; size_t start[1]; int l_val; char name[MAX_VAR_NAME_LENGTH+1]; char tmpstr[MAX_STR_LENGTH+1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* open appropriate variable, depending on obj_type and prop_name */ num_props = ex_get_num_props(exoid,obj_type); for (i=1; i<=num_props; i++) { switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(i)); break; case EX_EDGE_BLOCK: strcpy (name, VAR_ED_PROP(i)); break; case EX_FACE_BLOCK: strcpy (name, VAR_FA_PROP(i)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(i)); break; case EX_EDGE_SET: strcpy (name, VAR_ES_PROP(i)); break; case EX_FACE_SET: strcpy (name, VAR_FS_PROP(i)); break; case EX_ELEM_SET: strcpy (name, VAR_ELS_PROP(i)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(i)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(i)); break; case EX_FACE_MAP: strcpy (name, VAR_FAM_PROP(i)); break; case EX_EDGE_MAP: strcpy (name, VAR_EDM_PROP(i)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(i)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_get_prop",errmsg,exerrval); return(EX_FATAL); } if ((status = nc_inq_varid(exoid, name, &propid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate property array %s in file id %d", name, exoid); ex_err("ex_get_prop",errmsg,exerrval); return (EX_FATAL); } /* compare stored attribute name with passed property name */ memset(tmpstr, 0, MAX_STR_LENGTH+1); if ((status = nc_get_att_text(exoid, propid, ATT_PROP_NAME, tmpstr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get property name in file id %d", exoid); ex_err("ex_get_prop",errmsg,exerrval); return (EX_FATAL); } if (strcmp(tmpstr, prop_name) == 0) { found = TRUE; break; } } /* if property is not found, return warning */ if (!found) { exerrval = EX_BADPARAM; sprintf(errmsg, "Warning: %s property %s not defined in file id %d", ex_name_of_object(obj_type), prop_name, exoid); ex_err("ex_get_prop",errmsg,exerrval); return (EX_WARN); } /* find index into property array using obj_id; read value from property */ /* array at proper index; ex_id_lkup returns an index that is 1-based, */ /* but netcdf expects 0-based arrays so subtract 1 */ start[0] = ex_id_lkup (exoid, obj_type, obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: %s id %d is NULL in file id %d", ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_get_prop",errmsg,EX_MSG); return (EX_WARN); } else { exerrval = status; sprintf(errmsg, "Error: failed to locate id %d in %s property array in file id %d", obj_id, ex_name_of_object(obj_type), exoid); ex_err("ex_get_prop",errmsg,exerrval); return (EX_FATAL); } } start[0] = start[0] - 1; if ((status = nc_get_var1_int (exoid, propid, start, &l_val)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to read value in %s property array in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_get_prop",errmsg,exerrval); return (EX_FATAL); } *value = l_val; return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/0000755000175000017500000000000011606020250022231 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/exodusII_ext.h0000644000175000017500000001662211606020250025022 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __exodus_ext_h #define __exodus_ext_h #ifdef __cplusplus extern "C" { #endif /** * \defgroup APIStructs Structures used by external API functions. * @{ */ typedef struct ex_init_params { char title[MAX_LINE_LENGTH + 1]; int num_dim; int num_nodes; int num_edge; int num_edge_blk; int num_face; int num_face_blk; int num_elem; int num_elem_blk; int num_node_sets; int num_edge_sets; int num_face_sets; int num_side_sets; int num_elem_sets; int num_node_maps; int num_edge_maps; int num_face_maps; int num_elem_maps; } ex_init_params; typedef struct ex_block_params { int* edge_blk_id; char** edge_type; int* num_edge_this_blk; int* num_nodes_per_edge; int* num_attr_edge; int* face_blk_id; char** face_type; int* num_face_this_blk; int* num_nodes_per_face; int* num_attr_face; int* elem_blk_id; char** elem_type; int* num_elem_this_blk; int* num_nodes_per_elem; int* num_edges_per_elem; int* num_faces_per_elem; int* num_attr_elem; int define_maps; } ex_block_params; typedef struct ex_set_specs { int* sets_ids; int* num_entries_per_set; int* num_dist_per_set; int* sets_entry_index; int* sets_dist_index; int* sets_entry_list; int* sets_extra_list; void* sets_dist_fact; } ex_set_specs; typedef struct ex_var_params { int num_glob; int num_node; int num_edge; int* edge_var_tab; int num_face; int* face_var_tab; int num_elem; int* elem_var_tab; int num_nset; int* nset_var_tab; int num_eset; int* eset_var_tab; int num_fset; int* fset_var_tab; int num_sset; int* sset_var_tab; int num_elset; int* elset_var_tab; } ex_var_params; /* @} */ #ifndef EXODUS_EXPORT #define EXODUS_EXPORT extern #endif /* EXODUS_EXPORT */ /* (MODIFIED) Write Initialization Parameters */ EXODUS_EXPORT int ex_put_init_ext (int, const ex_init_params*); /* (MODIFIED) Read Initialization Parameters */ EXODUS_EXPORT int ex_get_init_ext (int, ex_init_params*); /* Write Node Edge Face or Element Number Map */ EXODUS_EXPORT int ex_put_num_map (int, ex_entity_type, int, const int*); /* Read Number Map */ EXODUS_EXPORT int ex_get_num_map (int, ex_entity_type, int, int*); /* Write Edge Face or Element Block Parameters */ EXODUS_EXPORT int ex_put_block (int, ex_entity_type, int, const char*, int, int, int, int, int); /* Read Edge Face or Element Block Parameters */ EXODUS_EXPORT int ex_get_block (int, ex_entity_type, int, char*, int*, int*, int*, int*, int*); /* Write All Edge Face and Element Block Parameters */ EXODUS_EXPORT int ex_put_concat_all_blocks(int, const ex_block_params*); /* Write Edge Face or Element Block Connectivity */ EXODUS_EXPORT int ex_put_conn (int, ex_entity_type, int, const int*, const int*, const int*); /* Read Edge Face or Element Block Connectivity */ EXODUS_EXPORT int ex_get_conn (int, ex_entity_type, int, int*, int*, int*); /* Write Edge Face or Element Block Attributes */ EXODUS_EXPORT int ex_put_attr (int, ex_entity_type, int, const void*); /* Read Edge Face or Element Block Attributes */ EXODUS_EXPORT int ex_get_attr (int, ex_entity_type, int, void*); /* Write One Edge Face or Element Block Attribute */ EXODUS_EXPORT int ex_put_one_attr (int, ex_entity_type, int, int, const void*); /* Read One Edge Face or Element Block Attribute */ EXODUS_EXPORT int ex_get_one_attr (int, ex_entity_type, int, int, void*); /* Write Edge Face or Element Block Attribute Names */ EXODUS_EXPORT int ex_put_attr_names (int, ex_entity_type, int, char**); /* Read Edge Face or Element Block Attribute Names */ EXODUS_EXPORT int ex_get_attr_names (int, ex_entity_type, int, char**); /* Write Node Edge Face or Side Set Parameters */ EXODUS_EXPORT int ex_put_set_param (int, ex_entity_type, int, int, int); /* Read Node Edge Face or Side Set Parameters */ EXODUS_EXPORT int ex_get_set_param (int, ex_entity_type, int, int*, int*); /* Write a Node Edge Face or Side Set */ EXODUS_EXPORT int ex_put_set (int, ex_entity_type, int, const int*, const int*); /* Read a Node Edge Face or Side Set */ EXODUS_EXPORT int ex_get_set (int, ex_entity_type, int, int*, int*); /* Write Node Edge Face or Side Set Distribution Factors */ EXODUS_EXPORT int ex_put_set_dist_fact (int, ex_entity_type, int, const void*); /* Read Node Edge Face or Side Set Distribution Factors */ EXODUS_EXPORT int ex_get_set_dist_fact (int, ex_entity_type, int, void*); /* Write Concatenated Node Edge Face or Side Sets */ EXODUS_EXPORT int ex_put_concat_sets (int, ex_entity_type, const ex_set_specs*); /* Read Concatenated Node Edge Face or Side Sets */ EXODUS_EXPORT int ex_get_concat_sets(int, ex_entity_type, ex_set_specs*); /* (MODIFIED) Write All Results Variables Parameters */ EXODUS_EXPORT int ex_put_all_var_param_ext(int, const ex_var_params*); /* Write Edge Face or Element Variable Values on Blocks or Sets at a Time Step */ EXODUS_EXPORT int ex_put_var (int, int, ex_entity_type, int, int, int, const void*); /* Read Edge Face or Element Variable Values Defined On Blocks or Sets at a Time Step */ EXODUS_EXPORT int ex_get_var (int, int, ex_entity_type, int, int, int, void*); /* Read Edge Face or Element Variable Values Defined On Blocks or Sets Through Time */ EXODUS_EXPORT int ex_get_var_time (int, ex_entity_type, int, int, int, int, void*); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* __exodus_ext_h */ xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/vtk_exodus2_mangle.h0000644000175000017500000002673011606020250026212 0ustar amckinstryamckinstry#ifndef vtk_exodus2_mangle_h #define vtk_exodus2_mangle_h /* This header file mangles all symbols exported from the exodus library. It is included in all files while building the exodus library. Due to namespace pollution, no exodus headers should be included in .h files in VTK. This is the way to recreate the list: nm bin/libvtkexodIIc.so |grep " [TRD] " | awk '{ print "#define "$3" vtk_exodus_"$3 }' | \ grep -v vtk_exodus__fini | grep -v vtk_exodus__init | sort also #define ex_create vtk_exodus_ex_create #define ex_open vtk_exodus_ex_open were changed to #define ex_create_int vtk_exodus_ex_create_int #define ex_open_int vtk_exodus_ex_open_int after the fact Note that _fini and _init should be excluded because they are not functions implemented by the library but are rather created by the linker and used when the shared library is loaded/unloaded from an executable. */ #define ex_dim_num_objects vtk_exodus_ex_dim_num_objects #define ex_get_attr_param vtk_exodus_ex_get_attr_param #define ex_get_counter_list vtk_exodus_ex_get_counter_list #define ex_get_err vtk_exodus_ex_get_err #define ex_get_id_map vtk_exodus_ex_get_id_map #define ex_get_stat_ptr vtk_exodus_ex_get_stat_ptr #define ex_get_truth_table vtk_exodus_ex_get_truth_table #define ex_get_variable_names vtk_exodus_ex_get_variable_names #define ex_get_variable_name vtk_exodus_ex_get_variable_name #define ex_get_variable_param vtk_exodus_ex_get_variable_param #define ex_inquire_int vtk_exodus_ex_inquire_int #define ex_name_of_object vtk_exodus_ex_name_of_object #define ex_put_attr_param vtk_exodus_ex_put_attr_param #define ex_put_id_map vtk_exodus_ex_put_id_map #define ex_put_truth_table vtk_exodus_ex_put_truth_table #define ex_put_variable_names vtk_exodus_ex_put_variable_names #define ex_put_variable_name vtk_exodus_ex_put_variable_name #define ex_put_variable_param vtk_exodus_ex_put_variable_param #define ex_rm_stat_ptr vtk_exodus_ex_rm_stat_ptr #define ex_var_type_to_ex_entity_type vtk_exodus_ex_var_type_to_ex_entity_type #define cpy_coord_def vtk_exodus_cpy_coord_def #define cpy_coord_val vtk_exodus_cpy_coord_val #define cpy_var_def vtk_exodus_cpy_var_def #define cpy_var_val vtk_exodus_cpy_var_val #define dbl_to_flt vtk_exodus_dbl_to_flt #define ex_catstr2 vtk_exodus_ex_catstr2 #define ex_catstr vtk_exodus_ex_catstr #define ex_close vtk_exodus_ex_close #define ex_comp_ws vtk_exodus_ex_comp_ws #define ex_conv_array vtk_exodus_ex_conv_array #define ex_conv_exit vtk_exodus_ex_conv_exit #define ex_conv_ini vtk_exodus_ex_conv_ini #define ex_copy vtk_exodus_ex_copy #define ex_create_int vtk_exodus_ex_create_int #define ex_cvt_nodes_to_sides vtk_exodus_ex_cvt_nodes_to_sides #define ex_dim_num_entries_in_object vtk_exodus_ex_dim_num_entries_in_object #define ex_err vtk_exodus_ex_err #define ex_get_all_times vtk_exodus_ex_get_all_times #define ex_get_attr_names vtk_exodus_ex_get_attr_names #define ex_get_attr vtk_exodus_ex_get_attr #define ex_get_block vtk_exodus_ex_get_block #define ex_get_concat_node_sets vtk_exodus_ex_get_concat_node_sets #define ex_get_concat_sets vtk_exodus_ex_get_concat_sets #define ex_get_concat_side_sets vtk_exodus_ex_get_concat_side_sets #define ex_get_conn vtk_exodus_ex_get_conn #define ex_get_coordinate_frames vtk_exodus_ex_get_coordinate_frames #define ex_get_coord_names vtk_exodus_ex_get_coord_names #define ex_get_coord vtk_exodus_ex_get_coord #define ex_get_cpu_ws vtk_exodus_ex_get_cpu_ws #define ex_get_dimension vtk_exodus_ex_get_dimension #define ex_get_elem_attr_names vtk_exodus_ex_get_elem_attr_names #define ex_get_elem_attr vtk_exodus_ex_get_elem_attr #define ex_get_elem_blk_ids vtk_exodus_ex_get_elem_blk_ids #define ex_get_elem_block vtk_exodus_ex_get_elem_block #define ex_get_elem_conn vtk_exodus_ex_get_elem_conn #define ex_get_elem_map vtk_exodus_ex_get_elem_map #define ex_get_elem_num_map vtk_exodus_ex_get_elem_num_map #define ex_get_elem_varid vtk_exodus_ex_get_elem_varid #define ex_get_elem_var_tab vtk_exodus_ex_get_elem_var_tab #define ex_get_elem_var_time vtk_exodus_ex_get_elem_var_time #define ex_get_elem_var vtk_exodus_ex_get_elem_var #define ex_get_file_item vtk_exodus_ex_get_file_item #define ex_get_glob_vars vtk_exodus_ex_get_glob_vars #define ex_get_glob_var_time vtk_exodus_ex_get_glob_var_time #define ex_get_ids vtk_exodus_ex_get_ids #define ex_get_info vtk_exodus_ex_get_info #define ex_get_init_ext vtk_exodus_ex_get_init_ext #define ex_get_init vtk_exodus_ex_get_init #define ex_get_map_param vtk_exodus_ex_get_map_param #define ex_get_map vtk_exodus_ex_get_map #define ex_get_names vtk_exodus_ex_get_names #define ex_get_name vtk_exodus_ex_get_name #define ex_get_nodal_varid_var vtk_exodus_ex_get_nodal_varid_var #define ex_get_nodal_varid vtk_exodus_ex_get_nodal_varid #define ex_get_nodal_var_time vtk_exodus_ex_get_nodal_var_time #define ex_get_nodal_var vtk_exodus_ex_get_nodal_var #define ex_get_node_map vtk_exodus_ex_get_node_map #define ex_get_node_num_map vtk_exodus_ex_get_node_num_map #define ex_get_node_set_dist_fact vtk_exodus_ex_get_node_set_dist_fact #define ex_get_node_set_ids vtk_exodus_ex_get_node_set_ids #define ex_get_node_set_param vtk_exodus_ex_get_node_set_param #define ex_get_node_set vtk_exodus_ex_get_node_set #define ex_get_nset_varid vtk_exodus_ex_get_nset_varid #define ex_get_nset_var_tab vtk_exodus_ex_get_nset_var_tab #define ex_get_nset_var vtk_exodus_ex_get_nset_var #define ex_get_num_map vtk_exodus_ex_get_num_map #define ex_get_num_props vtk_exodus_ex_get_num_props #define ex_get_object_truth_vector vtk_exodus_ex_get_object_truth_vector #define ex_get_one_attr vtk_exodus_ex_get_one_attr #define ex_get_one_elem_attr vtk_exodus_ex_get_one_elem_attr #define ex_get_partial_elem_map vtk_exodus_ex_get_partial_elem_map #define ex_get_prop_array vtk_exodus_ex_get_prop_array #define ex_get_prop_names vtk_exodus_ex_get_prop_names #define ex_get_prop vtk_exodus_ex_get_prop #define ex_get_qa vtk_exodus_ex_get_qa #define ex_get_set_dist_fact vtk_exodus_ex_get_set_dist_fact #define ex_get_set_param vtk_exodus_ex_get_set_param #define ex_get_set vtk_exodus_ex_get_set #define ex_get_side_set_dist_fact vtk_exodus_ex_get_side_set_dist_fact #define ex_get_side_set_ids vtk_exodus_ex_get_side_set_ids #define ex_get_side_set_node_count vtk_exodus_ex_get_side_set_node_count #define ex_get_side_set_node_list_len vtk_exodus_ex_get_side_set_node_list_len #define ex_get_side_set_node_list vtk_exodus_ex_get_side_set_node_list #define ex_get_side_set_param vtk_exodus_ex_get_side_set_param #define ex_get_side_set vtk_exodus_ex_get_side_set #define ex_get_sset_varid vtk_exodus_ex_get_sset_varid #define ex_get_sset_var_tab vtk_exodus_ex_get_sset_var_tab #define ex_get_sset_var vtk_exodus_ex_get_sset_var #define ex_get_time vtk_exodus_ex_get_time #define ex_get_varid_var vtk_exodus_ex_get_varid_var #define ex_get_varid vtk_exodus_ex_get_varid #define ex_get_var_names vtk_exodus_ex_get_var_names #define ex_get_var_name vtk_exodus_ex_get_var_name #define ex_get_var_param vtk_exodus_ex_get_var_param #define ex_get_var_tab vtk_exodus_ex_get_var_tab #define ex_get_var_time vtk_exodus_ex_get_var_time #define ex_get_var vtk_exodus_ex_get_var #define ex_header_size vtk_exodus_ex_header_size #define ex_id_lkup vtk_exodus_ex_id_lkup #define ex_inc_file_item vtk_exodus_ex_inc_file_item #define ex_inquire vtk_exodus_ex_inquire #define ex_int_iisort vtk_exodus_ex_int_iisort #define ex_int_iqsort vtk_exodus_ex_int_iqsort #define ex_int_median3 vtk_exodus_ex_int_median3 #define ex_iqsort vtk_exodus_ex_iqsort #define ex_large_model vtk_exodus_ex_large_model #define ex_name_of_map vtk_exodus_ex_name_of_map #define ex_name_var_of_object vtk_exodus_ex_name_var_of_object #define ex_open_int vtk_exodus_ex_open_int #define ex_opts vtk_exodus_ex_opts #define ex_put_all_var_param_ext vtk_exodus_ex_put_all_var_param_ext #define ex_put_all_var_param vtk_exodus_ex_put_all_var_param #define ex_put_attr_names vtk_exodus_ex_put_attr_names #define ex_put_attr vtk_exodus_ex_put_attr #define ex_put_block vtk_exodus_ex_put_block #define ex_put_concat_all_blocks vtk_exodus_ex_put_concat_all_blocks #define ex_put_concat_elem_block vtk_exodus_ex_put_concat_elem_block #define ex_put_concat_node_sets vtk_exodus_ex_put_concat_node_sets #define ex_put_concat_sets vtk_exodus_ex_put_concat_sets #define ex_put_concat_side_sets vtk_exodus_ex_put_concat_side_sets #define ex_put_concat_var_param vtk_exodus_ex_put_concat_var_param #define ex_put_conn vtk_exodus_ex_put_conn #define ex_put_coordinate_frames vtk_exodus_ex_put_coordinate_frames #define ex_put_coord_names vtk_exodus_ex_put_coord_names #define ex_put_coord vtk_exodus_ex_put_coord #define ex_put_elem_attr_names vtk_exodus_ex_put_elem_attr_names #define ex_put_elem_attr vtk_exodus_ex_put_elem_attr #define ex_put_elem_block vtk_exodus_ex_put_elem_block #define ex_put_elem_conn vtk_exodus_ex_put_elem_conn #define ex_put_elem_map vtk_exodus_ex_put_elem_map #define ex_put_elem_num_map vtk_exodus_ex_put_elem_num_map #define ex_put_elem_var_tab vtk_exodus_ex_put_elem_var_tab #define ex_put_elem_var vtk_exodus_ex_put_elem_var #define ex_put_glob_vars vtk_exodus_ex_put_glob_vars #define ex_put_info vtk_exodus_ex_put_info #define ex_put_init_ext vtk_exodus_ex_put_init_ext #define ex_put_init vtk_exodus_ex_put_init #define ex_put_map_param vtk_exodus_ex_put_map_param #define ex_put_map vtk_exodus_ex_put_map #define ex_put_names vtk_exodus_ex_put_names #define ex_put_name vtk_exodus_ex_put_name #define ex_put_nodal_varid_var vtk_exodus_ex_put_nodal_varid_var #define ex_put_nodal_var vtk_exodus_ex_put_nodal_var #define ex_put_node_map vtk_exodus_ex_put_node_map #define ex_put_node_num_map vtk_exodus_ex_put_node_num_map #define ex_put_node_set_dist_fact vtk_exodus_ex_put_node_set_dist_fact #define ex_put_node_set_param vtk_exodus_ex_put_node_set_param #define ex_put_node_set vtk_exodus_ex_put_node_set #define ex_put_nset_var_tab vtk_exodus_ex_put_nset_var_tab #define ex_put_nset_var vtk_exodus_ex_put_nset_var #define ex_put_num_map vtk_exodus_ex_put_num_map #define ex_put_one_attr vtk_exodus_ex_put_one_attr #define ex_put_one_elem_attr vtk_exodus_ex_put_one_elem_attr #define ex_put_partial_elem_map vtk_exodus_ex_put_partial_elem_map #define ex_put_prop_array vtk_exodus_ex_put_prop_array #define ex_put_prop_names vtk_exodus_ex_put_prop_names #define ex_put_prop vtk_exodus_ex_put_prop #define ex_put_qa vtk_exodus_ex_put_qa #define ex_put_set_dist_fact vtk_exodus_ex_put_set_dist_fact #define ex_put_set_param vtk_exodus_ex_put_set_param #define ex_put_set vtk_exodus_ex_put_set #define ex_put_side_set_dist_fact vtk_exodus_ex_put_side_set_dist_fact #define ex_put_side_set_param vtk_exodus_ex_put_side_set_param #define ex_put_side_set vtk_exodus_ex_put_side_set #define ex_put_sset_var_tab vtk_exodus_ex_put_sset_var_tab #define ex_put_sset_var vtk_exodus_ex_put_sset_var #define ex_put_time vtk_exodus_ex_put_time #define ex_put_varid_var vtk_exodus_ex_put_varid_var #define ex_put_var_names vtk_exodus_ex_put_var_names #define ex_put_var_name vtk_exodus_ex_put_var_name #define ex_put_var_param vtk_exodus_ex_put_var_param #define ex_put_var_tab vtk_exodus_ex_put_var_tab #define ex_put_var vtk_exodus_ex_put_var #define ex_rm_file_item vtk_exodus_ex_rm_file_item #define ex_swap vtk_exodus_ex_swap #define ex_update vtk_exodus_ex_update #define flt_to_dbl vtk_exodus_flt_to_dbl #define get_stat_ptr vtk_exodus_get_stat_ptr #define itol vtk_exodus_itol #define ltoi vtk_exodus_ltoi #define nc_flt_code vtk_exodus_nc_flt_code #define resize_buffer vtk_exodus_resize_buffer #define rm_stat_ptr vtk_exodus_rm_stat_ptr #define update_internal_structs vtk_exodus_update_internal_structs #endif /* vtk_exodus2_mangle.h */ xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/exodusII_test.h0000644000175000017500000000116411606020250025174 0ustar amckinstryamckinstry#ifndef __exodusII_test_h #define __exodusII_test_h #include "exodusII.h" /* Need these includes for vtkstd namespace and cout/cerr */ #include "vtkIOStream.h" #include "vtkObject.h" #include "vtkFloatingPointExceptions.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ int cCreateEdgeFace( int, char*[] ); int cReadEdgeFace( int, char*[] ); #ifdef __cplusplus } #endif /* __cplusplus */ inline int CreateEdgeFace( int argc, char* argv[] ) { return cCreateEdgeFace( argc, argv ); } inline int ReadEdgeFace( int argc, char* argv[] ) { return cReadEdgeFace( argc, argv ); } #endif /* __exodusII_test_h */ xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/vtkExodusII.h0000644000175000017500000000165311606020250024625 0ustar amckinstryamckinstry/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkExodusII.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __vtkExodusII_h #define __vtkExodusII_h /* this file makes sure any change in vtk_exodus2_mangle.h will trigger * a rebuild of the exodus reader in vtkHybrid package. * Files in Hybrid must include vtkExodusII.h instead of exodusII.h */ #include "exodusII.h" #include "vtk_exodus2_mangle.h" #endif /* #ifndef __vtkExodusII_h */ xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/CVS/0000755000175000017500000000000011606020250022664 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/CVS/Entries0000644000175000017500000000052011606020250024215 0ustar amckinstryamckinstry/exodusII.h/1.1/Wed Jan 6 16:33:51 2010// /exodusII_cfg.h.in/1.1/Wed Jan 6 16:33:53 2010// /exodusII_ext.h/1.1/Wed Jan 6 16:33:54 2010// /exodusII_int.h/1.1/Wed Jan 6 16:33:54 2010// /exodusII_test.h/1.1/Wed Jan 6 16:33:54 2010// /vtkExodusII.h/1.1/Wed Jan 6 16:33:54 2010// /vtk_exodus2_mangle.h/1.1/Wed Jan 6 16:33:54 2010// D xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/CVS/Repository0000644000175000017500000000004211606020250024762 0ustar amckinstryamckinstryXdmf/Utilities/vtkexodus2/include xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/CVS/Root0000644000175000017500000000006411606020250023532 0ustar amckinstryamckinstry:pserver:anonymous@public.kitware.com:/cvsroot/Xdmf xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/exodusII_cfg.h.in0000755000175000017500000000127311606020250025365 0ustar amckinstryamckinstry#ifndef __exodusII_cfg_h #define __exodusII_cfg_h #define EXODUSII_VERSION_MAJOR @EXODUSII_VERSION_MAJOR@ #define EXODUSII_VERSION_MINOR @EXODUSII_VERSION_MINOR@ #define EXODUSII_VERSION_PATCH @EXODUSII_VERSION_PATCH@ #define EXODUSII_VERSION "@EXODUSII_VERSION_MAJOR@.@EXODUSII_VERSION_MINOR@.@EXODUSII_VERSION_PATCH@" #if defined(_WIN32) && !defined(WIN32) # define WIN32 #endif #cmakedefine EXODUSII_BUILD_SHARED_LIBS #if defined(WIN32) && defined(EXODUSII_BUILD_SHARED_LIBS) # if defined(vtkexoIIc_EXPORTS) # define EXODUS_EXPORT __declspec( dllexport ) extern # else # define EXODUS_EXPORT __declspec( dllimport ) extern # endif #else # define EXODUS_EXPORT extern #endif #endif xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/exodusII.h0000755000175000017500000007114211606020250024143 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exodusII.h - Exodus II API include file * *****************************************************************************/ #ifndef EXODUS_II_HDR #define EXODUS_II_HDR #include "vtk_netcdf.h" #include "vtk_exodus2_mangle.h" #include "exodusII_cfg.h" /* #include "stddef.h" */ /* EXODUS II version number */ #define EX_API_VERS 4.81 #define EX_API_VERS_NODOT 481 #define EX_VERS EX_API_VERS /* * need following extern if this include file is used in a C++ * program, to keep the C++ compiler from mangling the function names. */ #ifdef __cplusplus extern "C" { #endif /* * The following are miscellaneous constants used in the EXODUS II * API. They should already be defined, but are left over from the * old days... */ #ifndef TRUE #define TRUE -1 #endif #ifndef FALSE #define FALSE 0 #endif /** * \defgroup FileVars Variables controlling the file creation mode. *@{ */ #define EX_NOCLOBBER 0 /**< Don't overwrite existing database, default */ #define EX_CLOBBER 1 /**< Overwrite existing database if it exists */ #define EX_NORMAL_MODEL 2 /**< disable mods that permit storage of larger models */ #define EX_LARGE_MODEL 4 /**< enable mods that permit storage of larger models */ #define EX_NETCDF4 8 /**< use the hdf5-based netcdf4 output */ #define EX_NOSHARE 16 /**< Do not open netcdf file in "share" mode */ #define EX_SHARE 32 /**< Do open netcdf file in "share" mode */ #define EX_READ 0 #define EX_WRITE 1 /*@}*/ /*! \sa ex_inquire() */ enum ex_inquiry { EX_INQ_FILE_TYPE = 1, /**< inquire EXODUS II file type*/ EX_INQ_API_VERS = 2, /**< inquire API version number */ EX_INQ_DB_VERS = 3, /**< inquire database version number */ EX_INQ_TITLE = 4, /**< inquire database title */ EX_INQ_DIM = 5, /**< inquire number of dimensions */ EX_INQ_NODES = 6, /**< inquire number of nodes */ EX_INQ_ELEM = 7, /**< inquire number of elements */ EX_INQ_ELEM_BLK = 8, /**< inquire number of element blocks */ EX_INQ_NODE_SETS = 9, /**< inquire number of node sets*/ EX_INQ_NS_NODE_LEN = 10, /**< inquire length of node set node list */ EX_INQ_SIDE_SETS = 11, /**< inquire number of side sets*/ EX_INQ_SS_NODE_LEN = 12, /**< inquire length of side set node list */ EX_INQ_SS_ELEM_LEN = 13, /**< inquire length of side set element list */ EX_INQ_QA = 14, /**< inquire number of QA records */ EX_INQ_INFO = 15, /**< inquire number of info records */ EX_INQ_TIME = 16, /**< inquire number of time steps in the database */ EX_INQ_EB_PROP = 17, /**< inquire number of element block properties */ EX_INQ_NS_PROP = 18, /**< inquire number of node set properties */ EX_INQ_SS_PROP = 19, /**< inquire number of side set properties */ EX_INQ_NS_DF_LEN = 20, /**< inquire length of node set distribution factor list*/ EX_INQ_SS_DF_LEN = 21, /**< inquire length of side set distribution factor list*/ EX_INQ_LIB_VERS = 22, /**< inquire API Lib vers number*/ EX_INQ_EM_PROP = 23, /**< inquire number of element map properties */ EX_INQ_NM_PROP = 24, /**< inquire number of node map properties */ EX_INQ_ELEM_MAP = 25, /**< inquire number of element maps */ EX_INQ_NODE_MAP = 26, /**< inquire number of node maps*/ EX_INQ_EDGE = 27, /**< inquire number of edges */ EX_INQ_EDGE_BLK = 28, /**< inquire number of edge blocks */ EX_INQ_EDGE_SETS = 29, /**< inquire number of edge sets */ EX_INQ_ES_LEN = 30, /**< inquire length of concat edge set edge list */ EX_INQ_ES_DF_LEN = 31, /**< inquire length of concat edge set dist factor list*/ EX_INQ_EDGE_PROP = 32, /**< inquire number of properties stored per edge block */ EX_INQ_ES_PROP = 33, /**< inquire number of properties stored per edge set */ EX_INQ_FACE = 34, /**< inquire number of faces */ EX_INQ_FACE_BLK = 35, /**< inquire number of face blocks */ EX_INQ_FACE_SETS = 36, /**< inquire number of face sets */ EX_INQ_FS_LEN = 37, /**< inquire length of concat face set face list */ EX_INQ_FS_DF_LEN = 38, /**< inquire length of concat face set dist factor list*/ EX_INQ_FACE_PROP = 39, /**< inquire number of properties stored per face block */ EX_INQ_FS_PROP = 40, /**< inquire number of properties stored per face set */ EX_INQ_ELEM_SETS = 41, /**< inquire number of element sets */ EX_INQ_ELS_LEN = 42, /**< inquire length of concat element set element list */ EX_INQ_ELS_DF_LEN = 43, /**< inquire length of concat element set dist factor list*/ EX_INQ_ELS_PROP = 44, /**< inquire number of properties stored per elem set */ EX_INQ_EDGE_MAP = 45, /**< inquire number of edge maps */ EX_INQ_FACE_MAP = 46, /**< inquire number of face maps */ EX_INQ_INVALID = -1}; typedef enum ex_inquiry ex_inquiry; /* properties */ enum ex_entity_type { EX_NODAL = 14, /**< nodal "block" for variables*/ EX_NODE_BLOCK = 14, /**< alias for EX_NODAL */ EX_NODE_SET = 2, /**< node set property code */ EX_EDGE_BLOCK = 6, /**< edge block property code */ EX_EDGE_SET = 7, /**< edge set property code */ EX_FACE_BLOCK = 8, /**< face block property code */ EX_FACE_SET = 9, /**< face set property code */ EX_ELEM_BLOCK = 1, /**< element block property code*/ EX_ELEM_SET = 10, /**< face set property code */ EX_SIDE_SET = 3, /**< side set property code */ EX_ELEM_MAP = 4, /**< element map property code */ EX_NODE_MAP = 5, /**< node map property code */ EX_EDGE_MAP = 11, /**< edge map property code */ EX_FACE_MAP = 12, /**< face map property code */ EX_GLOBAL = 13, /**< global "block" for variables*/ EX_INVALID = -1}; typedef enum ex_entity_type ex_entity_type; /** * ex_opts() function codes - codes are OR'ed into exopts */ enum ex_options { EX_DEFAULT = 0, EX_VERBOSE = 1, /**< verbose mode message flag */ EX_DEBUG = 2, /**< debug mode def */ EX_ABORT = 4 /**< abort mode flag def */ }; typedef enum ex_options ex_options; /** * \defgroup StringLengths maximum string lengths; * constants that are used as netcdf dimensions must be of type long * @{ */ /** Maximum length of an entity name, attribute name, variable name, QA record, element type name */ #define MAX_STR_LENGTH 32L /** Maximum length of the database title or an information record */ #define MAX_LINE_LENGTH 80L /** Maximum length of an error message passed to ex_err() function. Typically, internal use only */ #define MAX_ERR_LENGTH 256 /* @} */ #ifndef EXODUS_EXPORT #define EXODUS_EXPORT extern #endif /* EXODUS_EXPORT */ /* routines for file initialization i/o */ EXODUS_EXPORT int ex_close (int exoid); EXODUS_EXPORT int ex_cvt_nodes_to_sides(int exoid, int *num_elem_per_set, int *num_nodes_per_set, int *side_sets_elem_index, int *side_sets_node_index, int *side_sets_elem_list, int *side_sets_node_list, int *side_sets_side_list); EXODUS_EXPORT int ex_copy (int in_exoid, int out_exoid); #define ex_create(path, mode, comp_ws, io_ws) ex_create_int(path, mode, comp_ws, io_ws, EX_API_VERS_NODOT) EXODUS_EXPORT int ex_create_int (const char *path, int cmode, int *comp_ws, int *io_ws, int my_version); EXODUS_EXPORT int ex_get_all_times (int exoid, void *time_values); EXODUS_EXPORT int ex_get_concat_node_sets (int exoid, int *node_set_ids, int *num_nodes_per_set, int *num_df_per_set, int *node_sets_node_index, int *node_sets_df_index, int *node_sets_node_list, void *node_sets_dist_fact); EXODUS_EXPORT int ex_get_coord_names (int exoid, char **coord_names); EXODUS_EXPORT int ex_get_coord (int exoid, void *x_coor, void *y_coor, void *z_coor); EXODUS_EXPORT int ex_get_concat_side_sets (int exoid, int *side_set_ids, int *num_elem_per_set, int *num_dist_per_set, int *side_sets_elem_index, int *side_sets_dist_index, int *side_sets_elem_list, int *side_sets_side_list, void *side_sets_dist_fact); EXODUS_EXPORT int ex_get_elem_attr_names (int exoid, int elem_blk_id, char **names); EXODUS_EXPORT int ex_get_elem_attr (int exoid, int elem_blk_id, void *attrib); EXODUS_EXPORT int ex_get_ids (int exoid, ex_entity_type obj_type, int *ids); EXODUS_EXPORT int ex_get_elem_blk_ids (int exoid, int *ids); EXODUS_EXPORT int ex_get_elem_block (int exoid, int elem_blk_id, char *elem_type, int *num_elem_this_blk, int *num_nodes_per_elem, int *num_attr); EXODUS_EXPORT int ex_get_elem_conn (int exoid, int elem_blk_id, int *connect); EXODUS_EXPORT int ex_get_elem_map (int exoid, int map_id, int *elem_map); EXODUS_EXPORT int ex_get_elem_num_map (int exoid, int *elem_map); EXODUS_EXPORT int ex_get_elem_var (int exoid, int time_step, int elem_var_index, int elem_blk_id, int num_elem_this_blk, void *elem_var_vals); EXODUS_EXPORT int ex_get_elem_varid (int exoid, int *varid); EXODUS_EXPORT int ex_get_elem_var_time (int exoid, int elem_var_index, int elem_number, int beg_time_step, int end_time_step, void *elem_var_vals); EXODUS_EXPORT int ex_get_coordinate_frames(int exoid, int *nframes, int *cf_ids, void* pt_coordinates, char* tags); EXODUS_EXPORT int ex_get_glob_vars (int exoid, int time_step, int num_glob_vars, void *glob_var_vals); EXODUS_EXPORT int ex_get_glob_var_time (int exoid, int glob_var_index, int beg_time_step, int end_time_step, void *glob_var_vals); EXODUS_EXPORT int ex_get_info (int exoid, char **info); EXODUS_EXPORT int ex_get_init (int exoid, char *title, int *num_dim, int *num_nodes, int *num_elem, int *num_elem_blk, int *num_node_sets, int *num_side_sets); EXODUS_EXPORT int ex_get_map (int exoid, int *elem_map); EXODUS_EXPORT int ex_get_map_param (int exoid, int *num_node_maps, int *num_elem_maps); EXODUS_EXPORT int ex_get_name (int exoid, ex_entity_type obj_type, int entity_id, char *name); EXODUS_EXPORT int ex_get_names (int exoid, ex_entity_type obj_type, char **names); EXODUS_EXPORT int ex_get_node_map (int exoid, int map_id, int *node_map); EXODUS_EXPORT int ex_get_node_num_map (int exoid, int *node_map); EXODUS_EXPORT int ex_get_node_set_param (int exoid, int node_set_id, int *num_nodes_in_set, int *num_df_in_set); EXODUS_EXPORT int ex_get_node_set (int exoid, int node_set_id, int *node_set_node_list); EXODUS_EXPORT int ex_get_node_set_dist_fact (int exoid, int node_set_id, void *node_set_dist_fact); EXODUS_EXPORT int ex_get_node_set_ids (int exoid, int *ids); EXODUS_EXPORT int ex_get_nset_var_tab (int exoid, int num_nodesets, int num_nset_var, int *nset_var_tab); EXODUS_EXPORT int ex_get_nset_var (int exoid, int time_step, int nset_var_index, int nset_id, int num_node_this_nset, void *nset_var_vals); EXODUS_EXPORT int ex_get_nset_varid (int exoid, int *varid); EXODUS_EXPORT int ex_get_nodal_var (int exoid, int time_step, int nodal_var_index, int num_nodes, void *nodal_var_vals); EXODUS_EXPORT int ex_get_nodal_varid(int exoid, int *varid); EXODUS_EXPORT int ex_get_nodal_var_time (int exoid, int nodal_var_index, int node_number, int beg_time_step, int end_time_step, void *nodal_var_vals); EXODUS_EXPORT int ex_get_nodal_varid_var(int exoid, int time_step, int nodal_var_index, int num_nodes, int varid, void *nodal_var_vals); EXODUS_EXPORT int ex_get_one_elem_attr (int exoid, int elem_blk_id, int attrib_index, void *attrib); EXODUS_EXPORT int ex_get_prop_array (int exoid, ex_entity_type obj_type, const char *prop_name, int *values); EXODUS_EXPORT int ex_get_prop (int exoid, ex_entity_type obj_type, int obj_id, const char *prop_name, int *value); EXODUS_EXPORT int ex_get_partial_elem_map (int exoid, int map_id, int ent_start, int ent_count, int *elem_map); EXODUS_EXPORT int ex_get_prop_names (int exoid, ex_entity_type obj_type, char **prop_names); EXODUS_EXPORT int ex_get_qa (int exoid, char *qa_record[][4]); EXODUS_EXPORT int ex_get_side_set_node_list_len(int exoid, int side_set_id, int *side_set_node_list_len); EXODUS_EXPORT int ex_get_side_set_param (int exoid, int side_set_id, int *num_side_in_set, int *num_dist_fact_in_set); EXODUS_EXPORT int ex_get_side_set (int exoid, int side_set_id, int *side_set_elem_list, int *side_set_side_list); EXODUS_EXPORT int ex_get_side_set_node_count(int exoid, int side_set_id, int *side_set_node_cnt_list); EXODUS_EXPORT int ex_get_side_set_dist_fact (int exoid, int side_set_id, void *side_set_dist_fact); EXODUS_EXPORT int ex_get_side_set_ids (int exoid, int *ids); EXODUS_EXPORT int ex_get_side_set_node_list(int exoid, int side_set_id, int *side_set_node_cnt_list, int *side_set_node_list); EXODUS_EXPORT int ex_get_sset_var (int exoid, int time_step, int sset_var_index, int sset_id, int num_side_this_sset, void *sset_var_vals); EXODUS_EXPORT int ex_get_sset_var_tab (int exoid, int num_sidesets, int num_sset_var, int *sset_var_tab); EXODUS_EXPORT int ex_get_sset_varid (int exoid, int *varid); EXODUS_EXPORT int ex_get_time (int exoid, int time_step, void *time_value); EXODUS_EXPORT int ex_get_variable_names (int exoid, ex_entity_type obj_type, int num_vars, char *var_names[]); EXODUS_EXPORT int ex_get_var_names (int exoid, const char *var_type, int num_vars, char *var_names[]); EXODUS_EXPORT int ex_get_varid (int exoid, ex_entity_type obj_type, int *varid_arr); EXODUS_EXPORT int ex_get_variable_name (int exoid, ex_entity_type obj_type, int var_num, char *var_name); EXODUS_EXPORT int ex_get_var_name (int exoid, const char *var_type, int var_num, char *var_name); EXODUS_EXPORT int ex_get_var_param (int exoid, const char *var_type, int *num_vars); EXODUS_EXPORT int ex_get_variable_param (int exoid, ex_entity_type obj_type, int *num_vars); EXODUS_EXPORT int ex_get_object_truth_vector (int exoid, ex_entity_type var_type, int object_id, int num_var, int *var_vector); EXODUS_EXPORT int ex_get_truth_table (int exoid, ex_entity_type obj_type, int num_blk, int num_var, int *var_tab); EXODUS_EXPORT int ex_get_var_tab (int exoid, const char *var_type, int num_blk, int num_var, int *var_tab); EXODUS_EXPORT int ex_get_elem_var_tab (int exoid, int num_elem_blk, int num_elem_var, int *elem_var_tab); #define ex_open(path, mode, comp_ws, io_ws, version) ex_open_int(path, mode, comp_ws, io_ws, version, EX_API_VERS_NODOT) EXODUS_EXPORT int ex_open_int (const char *path, int mode, int *comp_ws, int *io_ws, float *version, int my_version); EXODUS_EXPORT int ex_put_attr_param (int exoid, ex_entity_type obj_type, int obj_id, int num_attrs); EXODUS_EXPORT int ex_get_attr_param (int exoid, ex_entity_type obj_type, int obj_id, int *num_attrs); EXODUS_EXPORT int ex_put_all_var_param (int exoid, int num_g, int num_n, int num_e, int *elem_var_tab, int num_m, int *nset_var_tab, int num_s, int *sset_var_tab); EXODUS_EXPORT int ex_put_concat_elem_block (int exoid, const int* elem_blk_id, char *elem_type[], const int* num_elem_this_blk, const int* num_nodes_per_elem, const int* num_attr, int define_maps); EXODUS_EXPORT int ex_put_concat_node_sets (int exoid, int *node_set_ids, int *num_nodes_per_set, int *num_dist_per_set, int *node_sets_node_index, int *node_sets_df_index, int *node_sets_node_list, void *node_sets_dist_fact); EXODUS_EXPORT int ex_put_concat_side_sets (int exoid, int *side_set_ids, int *num_elem_per_set, int *num_dist_per_set, int *side_sets_elem_index, int *side_sets_dist_index, int *side_sets_elem_list, int *side_sets_side_list, void *side_sets_dist_fact); EXODUS_EXPORT int ex_put_concat_var_param (int exoid, int num_g, int num_n, int num_e, int num_elem_blk, int *elem_var_tab); EXODUS_EXPORT int ex_put_coord_names (int exoid, char *coord_names[]); EXODUS_EXPORT int ex_put_coord (int exoid, const void *x_coor, const void *y_coor, const void *z_coor); EXODUS_EXPORT int ex_put_elem_attr_names(int exoid, int elem_blk_id, char *names[]); EXODUS_EXPORT int ex_put_elem_attr (int exoid, int elem_blk_id, const void *attrib); EXODUS_EXPORT int ex_put_elem_block (int exoid, int elem_blk_id, const char *elem_type, int num_elem_this_blk, int num_nodes_per_elem, int num_attr); EXODUS_EXPORT int ex_put_elem_conn (int exoid, int elem_blk_id, const int *connect); EXODUS_EXPORT int ex_put_elem_map (int exoid, int map_id, const int *elem_map); EXODUS_EXPORT int ex_put_id_map(int exoid, ex_entity_type obj_type, const int *map); EXODUS_EXPORT int ex_get_id_map(int exoid, ex_entity_type obj_type, int *map); EXODUS_EXPORT int ex_put_elem_num_map (int exoid, const int *elem_map); EXODUS_EXPORT int ex_put_elem_var (int exoid, int time_step, int elem_var_index, int elem_blk_id, int num_elem_this_blk, const void *elem_var_vals); EXODUS_EXPORT int ex_put_coordinate_frames(int exoid, int nframes, const int cf_ids[], void* pt_coordinates, const char* tags); EXODUS_EXPORT int ex_put_glob_vars (int exoid, int time_step, int num_glob_vars, const void *glob_var_vals); EXODUS_EXPORT int ex_put_info (int exoid, int num_info, char *info[]); EXODUS_EXPORT int ex_put_init (int exoid, const char *title, int num_dim, int num_nodes, int num_elem, int num_elem_blk, int num_node_sets, int num_side_sets); EXODUS_EXPORT int ex_put_map (int exoid, const int *elem_map); EXODUS_EXPORT int ex_put_map_param (int exoid, int num_node_maps, int num_elem_maps); EXODUS_EXPORT int ex_put_name (int exoid, ex_entity_type obj_type, int entity_id, const char *name); EXODUS_EXPORT int ex_put_names (int exoid, ex_entity_type obj_type, char *names[]); EXODUS_EXPORT int ex_put_nodal_var (int exoid, int time_step, int nodal_var_index, int num_nodes, const void *nodal_var_vals); EXODUS_EXPORT int ex_put_nodal_varid_var(int exoid, int time_step, int nodal_var_index, int num_nodes, int varid, const void *nodal_var_vals); EXODUS_EXPORT int ex_put_node_map (int exoid, int map_id, const int *node_map); EXODUS_EXPORT int ex_put_node_num_map (int exoid, const int *node_map); EXODUS_EXPORT int ex_put_node_set_param (int exoid, int node_set_id, int num_nodes_in_set, int num_dist_in_set); EXODUS_EXPORT int ex_put_node_set (int exoid, int node_set_id, const int *node_set_node_list); EXODUS_EXPORT int ex_put_node_set_dist_fact (int exoid, int node_set_id, const void *node_set_dist_fact); EXODUS_EXPORT int ex_put_nset_var (int exoid, int time_step, int nset_var_index, int nset_id, int num_nodes_this_nset, const void *nset_var_vals); EXODUS_EXPORT int ex_put_nset_var_tab (int exoid, int num_nset, int num_nset_var, int *nset_var_tab); EXODUS_EXPORT int ex_put_one_elem_attr (int exoid, int elem_blk_id, int attrib_index, const void *attrib); EXODUS_EXPORT int ex_put_partial_elem_map (int exoid, int map_id, int ent_start, int ent_count, const int *elem_map); EXODUS_EXPORT int ex_put_prop (int exoid, ex_entity_type obj_type, int obj_id, const char *prop_name, int value); EXODUS_EXPORT int ex_put_prop_array (int exoid, ex_entity_type obj_type, const char *prop_name, const int *values); EXODUS_EXPORT int ex_put_prop_names (int exoid, ex_entity_type obj_type, int num_props, char **prop_names); EXODUS_EXPORT int ex_put_qa (int exoid, int num_qa_records, char* qa_record[][4]); EXODUS_EXPORT int ex_put_side_set_param (int exoid, int side_set_id, int num_side_in_set, int num_dist_fact_in_set); EXODUS_EXPORT int ex_put_side_set (int exoid, int side_set_id, const int *side_set_elem_list, const int *side_set_side_list); EXODUS_EXPORT int ex_put_side_set_dist_fact (int exoid, int side_set_id, const void *side_set_dist_fact); EXODUS_EXPORT int ex_put_sset_var (int exoid, int time_step, int sset_var_index, int sset_id, int num_faces_this_sset, const void *sset_var_vals); EXODUS_EXPORT int ex_put_sset_var_tab (int exoid, int num_sset, int num_sset_var, int *sset_var_tab); EXODUS_EXPORT int ex_put_time (int exoid, int time_step, const void *time_value); EXODUS_EXPORT int ex_put_varid_var(int exoid, int time_step, int varid, int num_entity, const void *var_vals); EXODUS_EXPORT int ex_put_var_names (int exoid, const char *var_type, int num_vars, char *var_names[]); EXODUS_EXPORT int ex_put_var_name (int exoid, const char *var_type, int var_num, const char *var_name); EXODUS_EXPORT int ex_put_var_param (int exoid, const char *var_type, int num_vars); EXODUS_EXPORT int ex_put_variable_names (int exoid, ex_entity_type obj_type, int num_vars, char* var_names[]); EXODUS_EXPORT int ex_put_variable_name (int exoid, ex_entity_type obj_type, int var_num, const char *var_name); EXODUS_EXPORT int ex_put_variable_param (int exoid, ex_entity_type obj_type, int num_vars); EXODUS_EXPORT int ex_put_truth_table (int exoid, ex_entity_type obj_type, int num_blk, int num_var, int *var_tab); EXODUS_EXPORT int ex_put_var_tab (int exoid, const char *var_type, int num_blk, int num_var, int *var_tab); EXODUS_EXPORT int ex_put_elem_var_tab (int exoid, int num_elem_blk, int num_elem_var, int *elem_var_tab); EXODUS_EXPORT int ex_update (int exoid); EXODUS_EXPORT int ex_get_num_props (int exoid, ex_entity_type obj_type); EXODUS_EXPORT int ex_large_model(int exoid); EXODUS_EXPORT size_t ex_header_size(int exoid); EXODUS_EXPORT void ex_err(const char*, const char*, int); EXODUS_EXPORT void ex_get_err(const char** msg, const char** func, int* errcode); EXODUS_EXPORT void ex_opts(int options); EXODUS_EXPORT int ex_inquire(int exoid, int inquiry, int*, void*, char*); EXODUS_EXPORT int ex_inquire_int(int exoid, int inquiry); EXODUS_EXPORT int ex_get_varid_var(int exoid, int time_step, int varid, int num_entity, void *var_vals); /* ERROR CODE DEFINITIONS AND STORAGE */ extern int exerrval; /**< shared error return value */ extern int exoptval; /**< error reporting flag (default is quiet) */ const char* ex_name_of_object(ex_entity_type obj_type); ex_entity_type ex_var_type_to_ex_entity_type(char var_type); #ifdef __cplusplus } /* close brackets on extern "C" declaration */ #endif /** * \defgroup ErrorReturnCodes Exodus error return codes - exerrval return values * @{ */ #define EX_MEMFAIL 1000 /**< memory allocation failure flag def */ #define EX_BADFILEMODE 1001 /**< bad file mode def */ #define EX_BADFILEID 1002 /**< bad file id def */ #define EX_WRONGFILETYPE 1003 /**< wrong file type for function */ #define EX_LOOKUPFAIL 1004 /**< id table lookup failed */ #define EX_BADPARAM 1005 /**< bad parameter passed */ #define EX_MSG -1000 /**< message print code - no error implied */ #define EX_PRTLASTMSG -1001 /**< print last error message msg code */ #define EX_NULLENTITY -1006 /**< null entity found */ /* @} */ #include "exodusII_ext.h" #endif xdmf-2.1.dfsg.1/Utilities/vtkexodus2/include/exodusII_int.h0000755000175000017500000010603211606020250025012 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exodusII_int.h - ExodusII header file for internal Exodus call use only * * author - Sandia National Laboratories * Vic Yarberry - Added headers and error logging * * * environment - UNIX * * revision history - * * $Id: exodusII_int.h,v 1.1 2010-01-06 16:33:54 kwleiter Exp $ * **************************************************************************** */ #ifndef EXODUS_II_INT_HDR #define EXODUS_II_INT_HDR #include "netcdf.h" #ifndef __APPLE__ #if defined __STDC__ || defined __cplusplus #include #endif #endif #ifdef _MSC_VER # pragma warning ( disable : 4127 ) # pragma warning ( disable : 4706 ) # pragma warning ( disable : 4701 ) #endif #if defined(__BORLANDC__) #pragma warn -8004 /* "assigned a value that is never used" */ #pragma warn -8008 /* "condition is always true" */ #pragma warn -8060 /* "possibly incorrect assignment" */ #pragma warn -8066 /* "unreachable code" */ #endif #include #define MAX_VAR_NAME_LENGTH 20 /**< Internal use only */ /* for netCDF 3.4, we estimate the size of the header; * if estimate is larger than this max, set the estimate to this max; */ #define MAX_HEADER_SIZE 30000 /* this should be defined in ANSI C and C++, but just in case ... */ #ifndef NULL #define NULL 0 #endif /* Default "filesize" for newly created files. * Set to 0 for normal filesize setting. * Set to 1 for EXODUS_LARGE_MODEL setting to be the default */ #define EXODUS_DEFAULT_SIZE 1 /* Exodus error return codes - function return values: */ #define EX_FATAL -1 /* fatal error flag def */ #define EX_NOERR 0 /* no error flag def */ #define EX_WARN 1 /* warning flag def */ /* * This file contains defined constants that are used internally in the * EXODUS II API. * * The first group of constants refer to netCDF variables, attributes, or * dimensions in which the EXODUS II data are stored. Using the defined * constants will allow the names of the netCDF entities to be changed easily * in the future if needed. The first three letters of the constant identify * the netCDF entity as a variable (VAR), dimension (DIM), or attribute (ATT). * * NOTE: The entity name should not have any blanks in it. Blanks are * technically legal but some netcdf utilities (ncgen in particular) * fail when they encounter a blank in a name. * * DEFINED CONSTANT ENTITY NAME DATA STORED IN ENTITY */ #define ATT_FILE_TYPE "type" /* obsolete */ #define ATT_TITLE "title" /* the database title */ #define ATT_API_VERSION "api_version" /* the EXODUS II api vers # */ #define ATT_API_VERSION_BLANK "api version" /* the EXODUS II api vers # */ /* used for db version 2.01 */ /* and earlier */ #define ATT_VERSION "version" /* the EXODUS II file vers # */ #define ATT_FILESIZE "file_size" /* 1=large, 0=normal */ #define ATT_FLT_WORDSIZE "floating_point_word_size" /* word size of floating */ /* point numbers in file */ #define ATT_FLT_WORDSIZE_BLANK "floating point word size" /* word size of floating */ /* point numbers in file */ /* used for db version 2.01 */ /* and earlier */ #define DIM_NUM_NODES "num_nodes" /* # of nodes */ #define DIM_NUM_DIM "num_dim" /* # of dimensions; 2- or 3-d*/ #define DIM_NUM_EDGE "num_edge" /* # of edges (over all blks)*/ #define DIM_NUM_FACE "num_face" /* # of faces (over all blks)*/ #define DIM_NUM_ELEM "num_elem" /* # of elements */ #define DIM_NUM_EL_BLK "num_el_blk" /* # of element blocks */ #define DIM_NUM_ED_BLK "num_ed_blk" /* # of edge blocks */ #define DIM_NUM_FA_BLK "num_fa_blk" /* # of face blocks */ #define VAR_COORD "coord" /* nodal coordinates */ #define VAR_COORD_X "coordx" /* X-dimension coordinate */ #define VAR_COORD_Y "coordy" /* Y-dimension coordinate */ #define VAR_COORD_Z "coordz" /* Z-dimension coordinate */ #define VAR_NAME_COOR "coor_names" /* names of coordinates */ #define VAR_NAME_EL_BLK "eb_names" /* names of element blocks */ #define VAR_NAME_NS "ns_names" /* names of node sets */ #define VAR_NAME_SS "ss_names" /* names of side sets */ #define VAR_NAME_EM "emap_names" /* names of element maps */ #define VAR_NAME_EDM "edmap_names" /* names of edge maps */ #define VAR_NAME_FAM "famap_names" /* names of face maps */ #define VAR_NAME_NM "nmap_names" /* names of node maps */ #define VAR_NAME_ED_BLK "ed_names" /* names of edge blocks */ #define VAR_NAME_FA_BLK "fa_names" /* names of face blocks */ #define VAR_NAME_ES "es_names" /* names of edge sets */ #define VAR_NAME_FS "fs_names" /* names of face sets */ #define VAR_NAME_ELS "els_names" /* names of element sets */ #define VAR_STAT_EL_BLK "eb_status" /* element block status */ #define VAR_STAT_ECONN "econn_status" /* element block edge status */ #define VAR_STAT_FCONN "fconn_status" /* element block face status */ #define VAR_STAT_ED_BLK "ed_status" /* edge block status */ #define VAR_STAT_FA_BLK "fa_status" /* face block status */ #define VAR_ID_EL_BLK "eb_prop1" /* element block ids props */ #define VAR_ID_ED_BLK "ed_prop1" /* edge block ids props */ #define VAR_ID_FA_BLK "fa_prop1" /* face block ids props */ #define ATT_NAME_ELB "elem_type" /* element type names for */ /* each element block */ #define DIM_NUM_EL_IN_BLK(num) ex_catstr("num_el_in_blk",num) /* # of elements in element */ /* block num */ #define DIM_NUM_NOD_PER_EL(num) ex_catstr("num_nod_per_el",num) /* # of nodes per element in */ /* element block num */ #define DIM_NUM_ATT_IN_BLK(num) ex_catstr("num_att_in_blk",num) /* # of attributes in element*/ /* block num */ #define DIM_NUM_ED_IN_EBLK(num) ex_catstr("num_ed_in_blk",num) /* # of edges in edge */ /* block num */ #define DIM_NUM_NOD_PER_ED(num) ex_catstr("num_nod_per_ed",num) /* # of nodes per edge in */ /* edge block num */ #define DIM_NUM_EDG_PER_EL(num) ex_catstr("num_edg_per_el",num) /* # of edges per element in */ /* element block num */ #define DIM_NUM_ATT_IN_EBLK(num) ex_catstr("num_att_in_eblk",num) /* # of attributes in edge */ /* block num */ #define DIM_NUM_FA_IN_FBLK(num) ex_catstr("num_fa_in_blk",num) /* # of faces in face */ /* block num */ #define DIM_NUM_NOD_PER_FA(num) ex_catstr("num_nod_per_fa",num) /* # of nodes per face in */ /* face block num */ #define DIM_NUM_FAC_PER_EL(num) ex_catstr("num_fac_per_el",num) /* # of faces per element in */ /* element block num */ #define DIM_NUM_ATT_IN_FBLK(num) ex_catstr("num_att_in_fblk",num) /* # of attributes in face */ /* block num */ #define DIM_NUM_ATT_IN_NBLK "num_att_in_nblk" #define VAR_CONN(num) ex_catstr("connect",num) /* element connectivity for */ /* element block num */ #define VAR_ATTRIB(num) ex_catstr("attrib",num) /* list of attributes for */ /* element block num */ #define VAR_NAME_ATTRIB(num) ex_catstr("attrib_name",num) /* list of attribute names */ /* for element block num */ #define VAR_EB_PROP(num) ex_catstr("eb_prop",num) /* list of the numth property*/ /* for all element blocks */ #define VAR_ECONN(num) ex_catstr("edgconn",num) /* edge connectivity for */ /* element block num */ #define VAR_EBCONN(num) ex_catstr("ebconn",num) /* edge connectivity for */ /* edge block num */ #define VAR_EATTRIB(num) ex_catstr("eattrb",num) /* list of attributes for */ /* edge block num */ #define VAR_NAME_EATTRIB(num) ex_catstr("eattrib_name",num) /* list of attribute names */ /* for edge block num */ #define VAR_NATTRIB "nattrb" #define VAR_NAME_NATTRIB "nattrib_name" #define DIM_NUM_ATT_IN_NBLK "num_att_in_nblk" #define VAR_NSATTRIB(num) ex_catstr("nsattrb",num) #define VAR_NAME_NSATTRIB(num) ex_catstr("nsattrib_name",num) #define DIM_NUM_ATT_IN_NS(num) ex_catstr("num_att_in_ns",num) #define VAR_SSATTRIB(num) ex_catstr("ssattrb",num) #define VAR_NAME_SSATTRIB(num) ex_catstr("ssattrib_name",num) #define DIM_NUM_ATT_IN_SS(num) ex_catstr("num_att_in_ss",num) #define VAR_ESATTRIB(num) ex_catstr("esattrb",num) #define VAR_NAME_ESATTRIB(num) ex_catstr("esattrib_name",num) #define DIM_NUM_ATT_IN_ES(num) ex_catstr("num_att_in_es",num) #define VAR_FSATTRIB(num) ex_catstr("fsattrb",num) #define VAR_NAME_FSATTRIB(num) ex_catstr("fsattrib_name",num) #define DIM_NUM_ATT_IN_FS(num) ex_catstr("num_att_in_fs",num) #define VAR_ELSATTRIB(num) ex_catstr("elsattrb",num) #define VAR_NAME_ELSATTRIB(num) ex_catstr("elsattrib_name",num) #define DIM_NUM_ATT_IN_ELS(num) ex_catstr("num_att_in_els",num) #define VAR_ED_PROP(num) ex_catstr("ed_prop",num) /* list of the numth property*/ /* for all edge blocks */ #define VAR_FCONN(num) ex_catstr("facconn",num) /* face connectivity for */ /* element block num */ #define VAR_FBCONN(num) ex_catstr("fbconn",num) /* face connectivity for */ /* face block num */ #define VAR_FATTRIB(num) ex_catstr("fattrb",num) /* list of attributes for */ /* face block num */ #define VAR_NAME_FATTRIB(num) ex_catstr("fattrib_name",num) /* list of attribute names */ /* for face block num */ #define VAR_FA_PROP(num) ex_catstr("fa_prop",num) /* list of the numth property*/ /* for all face blocks */ #define ATT_PROP_NAME "name" /* name attached to element */ /* block, node set, side */ /* set, element map, or */ /* map properties */ #define VAR_MAP "elem_map" /* element order map */ /* obsolete, replaced by */ /* VAR_ELEM_MAP(num) */ #define DIM_NUM_SS "num_side_sets" /* # of side sets */ #define VAR_SS_STAT "ss_status" /* side set status */ #define VAR_SS_IDS "ss_prop1" /* side set id properties */ #define DIM_NUM_SIDE_SS(num) ex_catstr("num_side_ss",num) /* # of sides in side set num*/ #define DIM_NUM_DF_SS(num) ex_catstr("num_df_ss",num) /* # of distribution factors */ /* in side set num */ /*#define DIM_NUM_NOD_SS(num) ex_catstr("num_nod_ss",num) *** obsolete *** */ /* # of nodes in side set num*/ #define VAR_FACT_SS(num) ex_catstr("dist_fact_ss",num) /* the distribution factors */ /* for each node in side */ /* set num */ #define VAR_ELEM_SS(num) ex_catstr("elem_ss",num) /* list of elements in side */ /* set num */ #define VAR_SIDE_SS(num) ex_catstr("side_ss",num) /* list of sides in side set */ #define VAR_SS_PROP(num) ex_catstr("ss_prop",num) /* list of the numth property*/ /* for all side sets */ #define DIM_NUM_ES "num_edge_sets"/* # of edge sets */ #define VAR_ES_STAT "es_status" /* edge set status */ #define VAR_ES_IDS "es_prop1" /* edge set id properties */ #define DIM_NUM_EDGE_ES(num) ex_catstr("num_edge_es",num) /* # of edges in edge set num*/ #define DIM_NUM_DF_ES(num) ex_catstr("num_df_es",num) /* # of distribution factors */ /* in edge set num */ /*#define DIM_NUM_NOD_ES(num) ex_catstr("num_nod_es",num) *** obsolete *** */ /* # of nodes in edge set num*/ #define VAR_FACT_ES(num) ex_catstr("dist_fact_es",num) /* the distribution factors */ /* for each node in edge */ /* set num */ #define VAR_EDGE_ES(num) ex_catstr("edge_es",num) /* list of edges in edge */ /* set num */ #define VAR_ORNT_ES(num) ex_catstr("ornt_es",num) /* list of orientations in */ /* the edge set. */ #define VAR_ES_PROP(num) ex_catstr("es_prop",num) /* list of the numth property*/ /* for all edge sets */ #define DIM_NUM_FS "num_face_sets"/* # of face sets */ #define VAR_FS_STAT "fs_status" /* face set status */ #define VAR_FS_IDS "fs_prop1" /* face set id properties */ #define DIM_NUM_FACE_FS(num) ex_catstr("num_face_fs",num) /* # of faces in side set num*/ #define DIM_NUM_DF_FS(num) ex_catstr("num_df_fs",num) /* # of distribution factors */ /* in face set num */ /*#define DIM_NUM_NOD_FS(num) ex_catstr("num_nod_ss",num) *** obsolete *** */ /* # of nodes in face set num*/ #define VAR_FACT_FS(num) ex_catstr("dist_fact_fs",num) /* the distribution factors */ /* for each node in face */ /* set num */ #define VAR_FACE_FS(num) ex_catstr("face_fs",num) /* list of elements in face */ /* set num */ #define VAR_ORNT_FS(num) ex_catstr("ornt_fs",num) /* list of sides in side set */ #define VAR_FS_PROP(num) ex_catstr("fs_prop",num) /* list of the numth property*/ /* for all face sets */ #define DIM_NUM_ELS "num_elem_sets"/* # of elem sets */ #define DIM_NUM_ELE_ELS(num) ex_catstr("num_ele_els",num) /* # of elements in elem set */ /* num */ #define DIM_NUM_DF_ELS(num) ex_catstr("num_df_els",num) /* # of distribution factors */ /* in element set num */ #define VAR_ELS_STAT "els_status" /* elem set status */ #define VAR_ELS_IDS "els_prop1" /* elem set id properties */ #define VAR_ELEM_ELS(num) ex_catstr("elem_els",num) /* list of elements in elem */ /* set num */ #define VAR_FACT_ELS(num) ex_catstr("dist_fact_els",num) /* list of distribution */ /* factors in elem set num */ #define VAR_ELS_PROP(num) ex_catstr("els_prop",num) /* list of the numth property*/ /* for all elem sets */ #define DIM_NUM_NS "num_node_sets"/* # of node sets */ #define DIM_NUM_NOD_NS(num) ex_catstr("num_nod_ns",num) /* # of nodes in node set */ /* num */ #define DIM_NUM_DF_NS(num) ex_catstr("num_df_ns",num) /* # of distribution factors */ /* in node set num */ #define VAR_NS_STAT "ns_status" /* node set status */ #define VAR_NS_IDS "ns_prop1" /* node set id properties */ #define VAR_NODE_NS(num) ex_catstr("node_ns",num) /* list of nodes in node set */ /* num */ #define VAR_FACT_NS(num) ex_catstr("dist_fact_ns",num) /* list of distribution */ /* factors in node set num */ #define VAR_NS_PROP(num) ex_catstr("ns_prop",num) /* list of the numth property*/ /* for all node sets */ #define DIM_NUM_QA "num_qa_rec" /* # of QA records */ #define VAR_QA_TITLE "qa_records" /* QA records */ #define DIM_NUM_INFO "num_info" /* # of information records */ #define VAR_INFO "info_records" /* information records */ #define VAR_HIS_TIME "time_hist" /* obsolete */ #define VAR_WHOLE_TIME "time_whole" /* simulation times for whole*/ /* time steps */ #define VAR_ELEM_TAB "elem_var_tab" /* element variable truth */ /* table */ #define VAR_EBLK_TAB "edge_var_tab" /* edge variable truth table */ #define VAR_FBLK_TAB "face_var_tab" /* face variable truth table */ #define VAR_ELSET_TAB "elset_var_tab" /* elemset variable truth */ /* table */ #define VAR_SSET_TAB "sset_var_tab" /* sideset variable truth */ /* table */ #define VAR_FSET_TAB "fset_var_tab" /* faceset variable truth */ /* table */ #define VAR_ESET_TAB "eset_var_tab" /* edgeset variable truth */ /* table */ #define VAR_NSET_TAB "nset_var_tab" /* nodeset variable truth */ /* table */ #define DIM_NUM_GLO_VAR "num_glo_var" /* # of global variables */ #define VAR_NAME_GLO_VAR "name_glo_var" /* names of global variables */ #define VAR_GLO_VAR "vals_glo_var" /* values of global variables*/ #define DIM_NUM_NOD_VAR "num_nod_var" /* # of nodal variables */ #define VAR_NAME_NOD_VAR "name_nod_var" /* names of nodal variables */ #define VAR_NOD_VAR "vals_nod_var" /* values of nodal variables */ #define VAR_NOD_VAR_NEW(num) ex_catstr("vals_nod_var",num) /* values of nodal variables */ #define DIM_NUM_ELE_VAR "num_elem_var" /* # of element variables */ #define VAR_NAME_ELE_VAR "name_elem_var" /* names of element variables*/ #define VAR_ELEM_VAR(num1,num2) ex_catstr2("vals_elem_var",num1,"eb",num2) /* values of element variable*/ /* num1 in element block */ /* num2 */ #define DIM_NUM_EDG_VAR "num_edge_var" /* # of edge variables */ #define VAR_NAME_EDG_VAR "name_edge_var" /* names of edge variables */ #define VAR_EDGE_VAR(num1,num2) ex_catstr2("vals_edge_var",num1,"eb",num2) /* values of edge variable */ /* num1 in edge block num2 */ #define DIM_NUM_FAC_VAR "num_face_var" /* # of face variables */ #define VAR_NAME_FAC_VAR "name_face_var" /* names of face variables */ #define VAR_FACE_VAR(num1,num2) ex_catstr2("vals_face_var",num1,"fb",num2) /* values of face variable */ /* num1 in face block num2 */ #define DIM_NUM_NSET_VAR "num_nset_var" /* # of nodeset variables */ #define VAR_NAME_NSET_VAR "name_nset_var" /* names of nodeset variables*/ #define VAR_NS_VAR(num1,num2) ex_catstr2("vals_nset_var",num1,"ns",num2) /* values of nodeset variable*/ /* num1 in nodeset num2 */ #define DIM_NUM_ESET_VAR "num_eset_var" /* # of edgeset variables */ #define VAR_NAME_ESET_VAR "name_eset_var" /* names of edgeset variables*/ #define VAR_ES_VAR(num1,num2) ex_catstr2("vals_eset_var",num1,"es",num2) /* values of edgeset variable*/ /* num1 in edgeset num2 */ #define DIM_NUM_FSET_VAR "num_fset_var" /* # of faceset variables */ #define VAR_NAME_FSET_VAR "name_fset_var" /* names of faceset variables*/ #define VAR_FS_VAR(num1,num2) ex_catstr2("vals_fset_var",num1,"fs",num2) /* values of faceset variable*/ /* num1 in faceset num2 */ #define DIM_NUM_SSET_VAR "num_sset_var" /* # of sideset variables */ #define VAR_NAME_SSET_VAR "name_sset_var" /* names of sideset variables*/ #define VAR_SS_VAR(num1,num2) ex_catstr2("vals_sset_var",num1,"ss",num2) /* values of sideset variable*/ /* num1 in sideset num2 */ #define DIM_NUM_ELSET_VAR "num_elset_var" /* # of element set variables*/ #define VAR_NAME_ELSET_VAR "name_elset_var"/* names of elemset variables*/ #define VAR_ELS_VAR(num1,num2) ex_catstr2("vals_elset_var",num1,"es",num2) /* values of elemset variable*/ /* num1 in elemset num2 */ #define DIM_NUM_HIS_VAR "num_his_var" /* obsolete */ #define VAR_NAME_HIS_VAR "name_his_var" /* obsolete */ #define VAR_HIS_VAR "vals_his_var" /* obsolete */ #define DIM_STR "len_string" /* general dimension of */ /* length MAX_STR_LENGTH */ /* used for name lengths */ #define DIM_LIN "len_line" /* general dimension of */ /* length MAX_LINE_LENGTH */ /* used for long strings */ #define DIM_N4 "four" /* general dimension of */ /* length 4 */ #define DIM_TIME "time_step" /* unlimited (expandable) */ /* dimension for time steps*/ #define DIM_HTIME "hist_time_step"/* obsolete */ #define VAR_ELEM_NUM_MAP "elem_num_map" /* element numbering map */ /* obsolete, replaced by */ /* VAR_ELEM_MAP(num) */ #define VAR_FACE_NUM_MAP "face_num_map" /* face numbering map */ /* obsolete, replaced by */ /* VAR_FACE_MAP(num) */ #define VAR_EDGE_NUM_MAP "edge_num_map" /* edge numbering map */ /* obsolete, replaced by */ /* VAR_EDGE_MAP(num) */ #define VAR_NODE_NUM_MAP "node_num_map" /* node numbering map */ /* obsolete, replaced by */ /* VAR_NODE_MAP(num) */ #define DIM_NUM_EM "num_elem_maps" /* # of element maps */ #define VAR_ELEM_MAP(num) ex_catstr("elem_map",num) /* the numth element map */ #define VAR_EM_PROP(num) ex_catstr("em_prop",num) /* list of the numth property*/ /* for all element maps */ #define DIM_NUM_EDM "num_edge_maps" /* # of edge maps */ #define VAR_EDGE_MAP(num) ex_catstr("edge_map",num) /* the numth edge map */ #define VAR_EDM_PROP(num) ex_catstr("edm_prop",num) /* list of the numth property*/ /* for all edge maps */ #define DIM_NUM_FAM "num_face_maps" /* # of face maps */ #define VAR_FACE_MAP(num) ex_catstr("face_map",num) /* the numth face map */ #define VAR_FAM_PROP(num) ex_catstr("fam_prop",num) /* list of the numth property*/ /* for all face maps */ #define DIM_NUM_NM "num_node_maps" /* # of node maps */ #define VAR_NODE_MAP(num) ex_catstr("node_map",num) /* the numth node map */ #define VAR_NM_PROP(num) ex_catstr("nm_prop",num) /* list of the numth property*/ /* for all node maps */ #define NUM_CFRAMES "num_cframes" #define NUM_CFRAME9 "num_cframes_9" #define FRAME_COORDS "frame_coordinates" #define FRAME_IDS "frame_ids" #define FRAME_TAGS "frame_tags" enum ex_element_type { UNK = -1, /**< unknown entity */ NULL_ELEMENT= 0, TRIANGLE = 1, /**< Triangle entity */ QUAD = 2, /**< Quad entity */ HEX = 3, /**< Hex entity */ WEDGE = 4, /**< Wedge entity */ TETRA = 5, /**< Tetra entity */ TRUSS = 6, /**< Truss entity */ BEAM = 7, /**< Beam entity */ SHELL = 8, /**< Shell entity */ SPHERE = 9, /**< Sphere entity */ CIRCLE = 10, /**< Circle entity */ TRISHELL = 11, /**< Triangular Shell entity */ PYRAMID = 12 /**< Pyramid entity */ }; typedef enum ex_element_type ex_element_type; /* Internal structure declarations */ struct elem_blk_parm { char elem_type[33]; int elem_blk_id; int num_elem_in_blk; int num_nodes_per_elem; int num_sides; int num_nodes_per_side[6]; int num_attr; int elem_ctr; ex_element_type elem_type_val; }; struct list_item { /* for use with ex_get_file_item */ int exo_id; int value; struct list_item* next; }; struct obj_stats { int *id_vals; int *stat_vals; long num; int exoid; int valid_ids; int valid_stat; struct obj_stats *next; }; void ex_iqsort(int v[], int iv[], int count ); char* ex_catstr(const char*, int); char* ex_catstr2(const char*, int, const char*, int); const char* ex_dim_num_entries_in_object(ex_entity_type, int); const char* ex_dim_num_objects(ex_entity_type obj_type); char* ex_name_var_of_object( ex_entity_type, int, int ); char* ex_name_of_map( ex_entity_type, int ); enum convert_task { RTN_ADDRESS, READ_CONVERT, WRITE_CONVERT, WRITE_CONVERT_DOWN, WRITE_CONVERT_UP }; int ex_conv_ini (int exoid, int* comp_wordsize, int* io_wordsize, int file_wordsize); void ex_conv_exit (int exoid); nc_type nc_flt_code (int exoid); int ex_comp_ws (int exoid); int ex_get_cpu_ws(void); struct list_item** ex_get_counter_list(ex_entity_type obj_type); int ex_get_file_item (int, struct list_item**); int ex_inc_file_item (int, struct list_item**); void ex_rm_file_item (int, struct list_item**); extern struct obj_stats* exoII_eb; extern struct obj_stats* exoII_ed; extern struct obj_stats* exoII_fa; extern struct obj_stats* exoII_ns; extern struct obj_stats* exoII_es; extern struct obj_stats* exoII_fs; extern struct obj_stats* exoII_ss; extern struct obj_stats* exoII_els; extern struct obj_stats* exoII_em; extern struct obj_stats* exoII_edm; extern struct obj_stats* exoII_fam; extern struct obj_stats* exoII_nm; int ex_get_side_set_node_list_len (int, int, int*); struct obj_stats *ex_get_stat_ptr ( int, struct obj_stats**); void ex_rm_stat_ptr (int, struct obj_stats**); int ex_id_lkup (int exoid, ex_entity_type id_type, int num); int ex_get_dimension(int exoid, const char *dimtype, const char *label, size_t *count, int *dimid, const char *routine); #endif xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnsv.c0000644000175000017500000000616711606020250022276 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgssv - ex_get_nset_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int nset_var_index nodeset variable index * int nset_blk_id nodeset id * int num_node_this_nset number of nodes in this nodeset * * * exit conditions - * float* nset_var_vals array of nodeset variable values * * * revision history - * * $Id: exgnsv.c,v 1.1 2010-01-06 16:33:19 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the values of a single nodeset variable for one nodeset at * one time step in the database; assume the first time step and * nodeset variable index is 1 * \deprecated Use ex_get_var()(exoid, time_step, EX_NODE_SET, nset_var_index, nset_id, num_node_this_nset, nset_var_vals) instead */ int ex_get_nset_var (int exoid, int time_step, int nset_var_index, int nset_id, int num_node_this_nset, void *nset_var_vals) { return ex_get_var(exoid, time_step, EX_NODE_SET, nset_var_index, nset_id, num_node_this_nset, nset_var_vals); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expcset.c0000644000175000017500000004103211606020250022425 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expcss - ex_put_concat_sets * * entry conditions - * input parameters: * int exoid exodus file id * int set_type type of set * struct ex_set_specs* set_specs set specs structure * * exit conditions - * * revision history - * * $Id: expcset.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the set ID's, set entry count array, set entry pointers array, * set entry list, set extra list, and distribution factors list for * all the sets of the specified type. * \param exoid exodus file id * \param set_type type of set * \param set_specs set specs structure */ int ex_put_concat_sets (int exoid, ex_entity_type set_type, const struct ex_set_specs* set_specs) { int status; int temp; const int *set_ids = set_specs->sets_ids; const int *num_entries_per_set = set_specs->num_entries_per_set; const int *num_dist_per_set = set_specs->num_dist_per_set; const int *sets_entry_index = set_specs->sets_entry_index; const int *sets_dist_index = set_specs->sets_dist_index; const int *sets_entry_list = set_specs->sets_entry_list; const int *sets_extra_list = set_specs->sets_extra_list; const void *sets_dist_fact = set_specs->sets_dist_fact; char *cdum; int i, num_sets, cur_num_sets, dimid, varid, set_id_ndx, dims[1], *set_stat; float fdum; const float *flt_dist_fact; const double *dbl_dist_fact; char errmsg[MAX_ERR_LENGTH]; char* idsptr; char* statptr; char* numdfptr = NULL; char* factptr = NULL; char* elemptr = NULL; char* extraptr = NULL; ex_inquiry ex_inq_val; const int *extra_list; exerrval = 0; /* clear error code */ cdum = 0; /* initialize even though it is not used */ /* setup pointers based on set_type NOTE: there is another block that sets more stuff later ... */ if (set_type == EX_NODE_SET) { ex_inq_val = EX_INQ_NODE_SETS; idsptr = VAR_NS_IDS; statptr = VAR_NS_STAT; } else if (set_type == EX_EDGE_SET) { ex_inq_val = EX_INQ_EDGE_SETS; idsptr = VAR_ES_IDS; statptr = VAR_ES_STAT; } else if (set_type == EX_FACE_SET) { ex_inq_val = EX_INQ_FACE_SETS; idsptr = VAR_FS_IDS; statptr = VAR_FS_STAT; } else if (set_type == EX_SIDE_SET) { ex_inq_val = EX_INQ_SIDE_SETS; idsptr = VAR_SS_IDS; statptr = VAR_SS_STAT; } else if (set_type == EX_ELEM_SET) { ex_inq_val = EX_INQ_ELEM_SETS; idsptr = VAR_ELS_IDS; statptr = VAR_ELS_STAT; } else { exerrval = EX_FATAL; sprintf(errmsg, "Error: invalid set type (%d)", set_type); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &temp)) != NC_NOERR) { if (status == NC_EBADDIM) { exerrval = status; sprintf(errmsg, "Error: no %ss defined for file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to locate %ss defined in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } return (EX_FATAL); } /* inquire how many sets are to be stored */ if (ex_inquire(exoid, ex_inq_val, &num_sets, &fdum, cdum) != NC_NOERR) { sprintf(errmsg, "Error: failed to get number of %ss defined for file id %d", ex_name_of_object(set_type), exoid); /* use error val from inquire */ ex_err("ex_put_concat_sets",errmsg,exerrval); return (EX_FATAL); } /* Fill out set status array */ /* First, allocate space for the status list */ if (!(set_stat= malloc(num_sets*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for %s status array in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); return (EX_FATAL); } for (i=0;i= num_sets) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of %ss (%d) defined in file id %d", ex_name_of_object(set_type), num_sets,exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); goto error_ret; } /* NOTE: ex_inc_file_item is used to find the number of sets for a specific file and returns that value incremented. */ cur_num_sets=ex_inc_file_item(exoid, ex_get_counter_list(set_type)); set_id_ndx = cur_num_sets + 1; /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { elemptr = VAR_NODE_NS(set_id_ndx); extraptr = NULL; /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */ numdfptr = DIM_NUM_NOD_NS(set_id_ndx); factptr = VAR_FACT_NS(set_id_ndx); } else if (set_type == EX_EDGE_SET) { elemptr = VAR_EDGE_ES(set_id_ndx); extraptr = VAR_ORNT_ES(set_id_ndx); numdfptr = DIM_NUM_DF_ES(set_id_ndx); factptr = VAR_FACT_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { elemptr = VAR_FACE_FS(set_id_ndx); extraptr = VAR_ORNT_FS(set_id_ndx); numdfptr = DIM_NUM_DF_FS(set_id_ndx); factptr = VAR_FACT_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { elemptr = VAR_ELEM_SS(set_id_ndx); extraptr = VAR_SIDE_SS(set_id_ndx); numdfptr = DIM_NUM_DF_SS(set_id_ndx); factptr = VAR_FACT_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { elemptr = VAR_ELEM_ELS(set_id_ndx); extraptr = NULL; numdfptr = DIM_NUM_DF_ELS(set_id_ndx); factptr = VAR_FACT_ELS(set_id_ndx); } /* define dimension for number of entries per set */ if (num_entries_per_set[i] == 0) /* Is this a NULL set? */ continue; /* Do not create anything for NULL sets! */ if ((status = nc_def_dim(exoid, ex_dim_num_entries_in_object(set_type, set_id_ndx), num_entries_per_set[i], &dimid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: %s entry count %d already defined in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define number of entries for %s %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } goto error_ret; } /* create element list variable for set */ dims[0] = dimid; if ((status = nc_def_var(exoid,elemptr,NC_INT,1,dims, &temp)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: element list already exists for %s %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to create element list for %s %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } /* create extra list variable for set (only for edge, face and side sets) */ if (extraptr) { if ((status = nc_def_var(exoid,extraptr,NC_INT,1,dims, &temp)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: extra list already exists for %s %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to create extra list for %s %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } } /* define dimension for number of dist factors per set */ /* NOTE: only define df count if the dist factors exist! */ if (num_dist_per_set[i] > 0) { if (set_type == EX_NODE_SET) { if (num_dist_per_set[i] != num_entries_per_set[i]) { exerrval = EX_FATAL; sprintf(errmsg, "Error: # dist fact (%d) not equal to # nodes (%d) in node set %d file id %d", num_dist_per_set[i], num_entries_per_set[i], set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* resuse dimid from entry lists */ } else { if ((status = nc_def_dim(exoid, numdfptr, num_dist_per_set[i], &dimid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: %s df count %d already defined in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define %s df count for set %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } goto error_ret; } } /* create distribution factor list variable for set */ dims[0] = dimid; if ((status = nc_def_var(exoid, factptr, nc_flt_code(exoid), 1, dims, &temp)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: dist factor list already exists for %s %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to create dist factor list for %s %d in file id %d", ex_name_of_object(set_type), set_ids[i],exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } } /* end define dist factors */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete definition in file id %d", exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); return (EX_FATAL); } /* Next, fill out set ids array */ /* first get id of set ids array variable */ if ((status = nc_inq_varid(exoid, idsptr, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s ids array in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); return (EX_FATAL); } /* then, write out set id list */ status = nc_put_var_int(exoid, varid, set_ids); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s id array in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); return (EX_FATAL); } /* If the sets_entry_index is passed in as a NULL pointer, then * the user only wants us to define the sets and not populate * the data structures. */ if (sets_entry_index == 0) return(EX_NOERR); /* Now, use ExodusII call to store sets */ for (i=0; i 0) { /* store dist factors if required */ if (ex_put_set_dist_fact(exoid, set_type, set_ids[i], &(flt_dist_fact[sets_dist_index[i]])) == -1) { sprintf(errmsg, "Error: failed to store %s %d dist factors for file id %d", ex_name_of_object(set_type), set_ids[i],exoid); /* use error val from exodusII routine */ ex_err("ex_put_concat_sets",errmsg,exerrval); return (EX_FATAL); } } } else if (ex_comp_ws(exoid) == sizeof(double)) { dbl_dist_fact = sets_dist_fact; if (num_dist_per_set[i] > 0) { /* only store if they exist */ if (ex_put_set_dist_fact(exoid, set_type, set_ids[i], &(dbl_dist_fact[sets_dist_index[i]])) == -1) { sprintf(errmsg, "Error: failed to store %s %d dist factors for file id %d", ex_name_of_object(set_type), set_ids[i],exoid); /* use error val from exodusII routine */ ex_err("ex_put_concat_sets",errmsg,exerrval); return (EX_FATAL); } } } else { /* unknown floating point word size */ exerrval = EX_BADPARAM; sprintf(errmsg, "Error: unsupported floating point word size %d for file id %d", ex_comp_ws(exoid), exoid); ex_err("ex_put_concat_sets", errmsg, exerrval); return (EX_FATAL); } } return(EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_concat_sets",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgtt.c0000644000175000017500000000550211606020250022107 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvtt - ex_get_var_tab * * entry conditions - * input parameters: * int exoid exodus file id * int num_blk number of blocks * int num_var number of variables * * exit conditions - * int* var_tab element variable truth table array * * $Id: exgtt.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" #include /*! * reads the EXODUS II specified variable truth table from the database * \deprecated Use ex_get_truth_table()(exoid, obj_type, num_blk, num_var, var_tab) */ int ex_get_var_tab (int exoid, const char *var_type, int num_blk, int num_var, int *var_tab) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return ex_get_truth_table(exoid, obj_type, num_blk, num_var, var_tab); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvartab.c0000644000175000017500000003172111606020250022752 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvtt - ex_put_truth_table * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type object type * int num_blk number of blocks * int num_var number of variables * int* variable_table variable truth table array * * exit conditions - * * revision history - * * $Id: expvartab.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the EXODUS II variable truth table to the database; also, * creates netCDF variables in which to store EXODUS II variable * values; although this table isn't required (because the netCDF * variables can also be created in ex_put_var), this call will save * tremendous time because all of the variables are defined at once * while the file is in define mode, rather than going in and out of * define mode (causing the entire file to be copied over and over) * which is what occurs when the variables are defined in ex_put_var * \param exoid exodus file id * \param obj_type object type * \param num_blk number of blocks * \param num_var number of variables * \param *var_tab variable truth table array */ int ex_put_truth_table (int exoid, ex_entity_type obj_type, int num_blk, int num_var, int *var_tab) { int numelblkdim, numelvardim, timedim, dims[2], varid; char *sta_type, *tab_type; size_t num_entity = 0; size_t num_var_db = 0; int *stat_vals; int i, j, k, id, *ids; int status; char errmsg[MAX_ERR_LENGTH]; const char* routine = "ex_put_truth_table"; /* * The ent_type and the var_name are used to build the netcdf * variables name. Normally this is done via a macro defined in * exodusII_int.h */ const char* ent_type = NULL; const char* var_name = NULL; const char* ent_size = NULL; exerrval = 0; /* clear error code */ ex_get_dimension(exoid, ex_dim_num_objects(obj_type), ex_name_of_object(obj_type), &num_entity, &numelblkdim, routine); if (obj_type == EX_ELEM_BLOCK) { ex_get_dimension(exoid, DIM_NUM_ELE_VAR, "element variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_ELEM_TAB, &varid); var_name = "vals_elem_var"; ent_type = "eb"; ent_size = "num_el_in_blk"; sta_type = VAR_STAT_EL_BLK; tab_type = VAR_ELEM_TAB; } else if (obj_type == EX_EDGE_BLOCK) { ex_get_dimension(exoid, DIM_NUM_EDG_VAR, "edge block variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_EBLK_TAB, &varid); var_name = "vals_edge_var"; ent_type = "eb"; ent_size = "num_ed_in_blk"; sta_type = VAR_STAT_ED_BLK; tab_type = VAR_EBLK_TAB; } else if (obj_type == EX_FACE_BLOCK) { ex_get_dimension(exoid, DIM_NUM_FAC_VAR, "face block variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_FBLK_TAB, &varid); var_name = "vals_face_var"; ent_type = "fb"; ent_size = "num_fa_in_blk"; sta_type = VAR_STAT_FA_BLK; tab_type = VAR_FBLK_TAB; } else if (obj_type == EX_SIDE_SET) { ex_get_dimension(exoid, DIM_NUM_SSET_VAR, "sideset variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_SSET_TAB, &varid); var_name = "vals_sset_var"; ent_type = "ss"; ent_size = "num_side_ss"; sta_type = VAR_SS_STAT; tab_type = VAR_SSET_TAB; } else if (obj_type == EX_NODE_SET) { ex_get_dimension(exoid, DIM_NUM_NSET_VAR, "nodeset variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_NSET_TAB, &varid); var_name = "vals_nset_var"; ent_type = "ns"; ent_size = "num_nod_ns"; sta_type = VAR_NS_STAT; tab_type = VAR_NSET_TAB; } else if (obj_type == EX_EDGE_SET) { ex_get_dimension(exoid, DIM_NUM_ESET_VAR, "edge set variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_ESET_TAB, &varid); var_name = "vals_eset_var"; ent_type = "es"; ent_size = "num_edge_es"; sta_type = VAR_ES_STAT; tab_type = VAR_ESET_TAB; } else if (obj_type == EX_FACE_SET) { ex_get_dimension(exoid, DIM_NUM_FSET_VAR, "face set variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_FSET_TAB, &varid); var_name = "vals_fset_var"; ent_type = "fs"; ent_size = "num_face_fs"; sta_type = VAR_FS_STAT; tab_type = VAR_FSET_TAB; } else if (obj_type == EX_ELEM_SET) { ex_get_dimension(exoid, DIM_NUM_ELSET_VAR, "element set variables", &num_var_db, &numelvardim, routine); status = nc_inq_varid (exoid, VAR_ELSET_TAB, &varid); var_name = "vals_elset_var"; ent_type = "es"; ent_size = "num_ele_els"; sta_type = VAR_ELS_STAT; tab_type = VAR_ELSET_TAB; } else { /* invalid variable type */ exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid variable type %d specified in file id %d", obj_type, exoid); ex_err("ex_get_varid",errmsg,exerrval); return (EX_WARN); } if (num_entity == (size_t)-1 || num_var_db == (size_t)-1) return (EX_FATAL); if (num_entity != (size_t)num_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: # of %s doesn't match those defined in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_get_var_tab",errmsg,exerrval); return (EX_FATAL); } if (num_var_db != (size_t)num_var) { exerrval = EX_FATAL; sprintf(errmsg, "Error: # of %s variables doesn't match those defined in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_get_var_tab",errmsg,exerrval); return (EX_FATAL); } /* get block IDs */ if (!(ids = malloc(num_blk*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate memory for %s id array for file id %d", ex_name_of_object(obj_type), exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } /* Get status array for later use */ if (!(stat_vals = malloc(num_blk*sizeof(int)))) { exerrval = EX_MEMFAIL; free(ids); sprintf(errmsg, "Error: failed to allocate memory for %s status array for file id %d", ex_name_of_object(obj_type), exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } ex_get_ids (exoid, obj_type, ids); status = nc_inq_varid (exoid, sta_type, &varid); /* get variable id of status array */ if (status == NC_NOERR) { /* if status array exists (V 2.01+), use it, otherwise assume object exists to be backward compatible */ if ((status = nc_get_var_int (exoid, varid, stat_vals)) != NC_NOERR) { exerrval = status; free(stat_vals); sprintf(errmsg, "Error: failed to get %s status array from file id %d", ex_name_of_object(obj_type), exoid); ex_err("put_var_tab",errmsg,exerrval); return (EX_FATAL); } } else { /* status array doesn't exist (V2.00), dummy one up for later checking */ for(i=0;i #include /*! * writes the name of a particular results variable to the database * \param exoid exodus file id * \param obj_type variable type * \param var_num variable number name to write 1..num_var * \param *var_name ptr of variable name */ int ex_put_variable_name (int exoid, ex_entity_type obj_type, int var_num, const char *var_name) { int status; int varid, dimid; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; const char* vname; exerrval = 0; /* clear error code */ /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_STR, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_var_name",errmsg,exerrval); return (EX_FATAL); } /* inquire previously defined variables */ switch (obj_type) { case EX_GLOBAL: vname = VAR_NAME_GLO_VAR; break; case EX_NODAL: vname = VAR_NAME_NOD_VAR; break; case EX_EDGE_BLOCK: vname = VAR_NAME_EDG_VAR; break; case EX_FACE_BLOCK: vname = VAR_NAME_FAC_VAR; break; case EX_ELEM_BLOCK: vname = VAR_NAME_ELE_VAR; break; case EX_NODE_SET: vname = VAR_NAME_NSET_VAR; break; case EX_EDGE_SET: vname = VAR_NAME_ESET_VAR; break; case EX_FACE_SET: vname = VAR_NAME_FSET_VAR; break; case EX_SIDE_SET: vname = VAR_NAME_SSET_VAR; break; case EX_ELEM_SET: vname = VAR_NAME_ELSET_VAR; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Invalid variable type (%d) given for file id %d", obj_type, exoid ); ex_err( "ex_put_variable_name", errmsg, exerrval ); return (EX_WARN); } if ((status = nc_inq_varid(exoid, vname, &varid)) != NC_NOERR) { exerrval = status; sprintf( errmsg, "Warning: no %s variables names stored in file id %d", ex_name_of_object(obj_type), exoid ); ex_err("ex_put_variable_name",errmsg,exerrval); return (EX_WARN); } /* write EXODUS variable name */ start[0] = var_num-1; start[1] = 0; count[0] = 1; count[1] = strlen(var_name) + 1; if ((status = nc_put_vara_text(exoid, varid, start, count, var_name)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s variable name %d in file id %d", ex_name_of_object(obj_type), var_num, exoid); ex_err("ex_put_variable_name",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvarparam.c0000644000175000017500000001042711606020250023273 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvp - ex_get_variable_param * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type variable type * * exit conditions - * int* num_vars number of variables in database * * revision history - * * $Id: exgvarparam.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * reads the number of global, nodal, or element variables that are * stored in the database */ int ex_get_variable_param (int exoid, ex_entity_type obj_type, int *num_vars) { int dimid; size_t dimlen; char errmsg[MAX_ERR_LENGTH]; const char* dnumvar; int status; exerrval = 0; /* clear error code */ *num_vars = 0; switch (obj_type) { case EX_GLOBAL: dnumvar = DIM_NUM_GLO_VAR; break; case EX_NODAL: dnumvar = DIM_NUM_NOD_VAR; break; case EX_EDGE_BLOCK: dnumvar = DIM_NUM_EDG_VAR; break; case EX_FACE_BLOCK: dnumvar = DIM_NUM_FAC_VAR; break; case EX_ELEM_BLOCK: dnumvar = DIM_NUM_ELE_VAR; break; case EX_NODE_SET: dnumvar = DIM_NUM_NSET_VAR; break; case EX_EDGE_SET: dnumvar = DIM_NUM_ESET_VAR; break; case EX_FACE_SET: dnumvar = DIM_NUM_FSET_VAR; break; case EX_SIDE_SET: dnumvar = DIM_NUM_SSET_VAR; break; case EX_ELEM_SET: dnumvar = DIM_NUM_ELSET_VAR; break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Warning: invalid variable type %d requested from file id %d", obj_type, exoid); ex_err("ex_get_var_param",errmsg,exerrval); return (EX_WARN); } if ((status = nc_inq_dimid (exoid, dnumvar, &dimid)) != NC_NOERR) { *num_vars = 0; if (status == NC_EBADDIM) return(EX_NOERR); /* no global variables defined */ else { exerrval = status; sprintf(errmsg, "Error: failed to locate %s variable names in file id %d", ex_name_of_object(obj_type),exoid); ex_err("ex_get_var_param",errmsg,exerrval); return (EX_FATAL); } } if ((status = nc_inq_dimlen(exoid, dimid, &dimlen)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of %s variables in file id %d", ex_name_of_object(obj_type),exoid); ex_err("ex_get_var_param",errmsg,exerrval); return (EX_FATAL); } *num_vars = dimlen; return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnvt.c0000755000175000017500000001263611606020250022300 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnvt - ex_get_nodal_var_time * * entry conditions - * input parameters: * int exoid exodus file id * int nodal_var_index index of desired nodal variable * int node_number number of desired node * int beg_time_step starting time step * int end_time_step finishing time step * * exit conditions - * float* nodal_var_vals array of nodal variable values * * revision history - * * $Id: exgnvt.c,v 1.1 2010-01-06 16:33:27 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the values of a nodal variable for a single node through a * specified number of time steps in the database; assume the first time * step, nodal variable index, and node are numbered 1 */ int ex_get_nodal_var_time (int exoid, int nodal_var_index, int node_number, int beg_time_step, int end_time_step, void *nodal_var_vals) { int status; int varid; size_t start[3], count[3]; float fdum; char *cdum = 0; char errmsg[MAX_ERR_LENGTH]; /* inquire previously defined variable */ if (end_time_step < 0) { /* user is requesting the maximum time step; we find this out using the * database inquire function to get the number of time steps; the ending * time step number is 1 less due to 0 based array indexing in C */ if ((status = ex_inquire (exoid, EX_INQ_TIME, &end_time_step, &fdum, cdum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of time steps in file id %d", exoid); ex_err("ex_get_nodal_var_time",errmsg,exerrval); return (EX_FATAL); } } end_time_step--; if (ex_large_model(exoid) == 0) { /* read values of the nodal variable; * assume node number is 1-based (first node is numbered 1); adjust * so it is 0-based */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", nodal_var_index, exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --beg_time_step; start[1] = --nodal_var_index; start[2] = --node_number; count[0] = end_time_step - beg_time_step + 1; count[1] = 1; count[2] = 1; } else { if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(nodal_var_index), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", nodal_var_index, exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } /* read values of the nodal variable; * assume node number is 1-based (first node is numbered 1); adjust * so it is 0-based */ start[0] = --beg_time_step; start[1] = --node_number; count[0] = end_time_step - beg_time_step + 1; count[1] = 1; } if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, nodal_var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, nodal_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get nodal variables in file id %d", exoid); ex_err("ex_get_nodal_var_time",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvtt.c0000755000175000017500000000547511606020250022311 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvtt - ex_get_elem_var_tab * * entry conditions - * input parameters: * int exoid exodus file id * int num_elem_blk number of element blocks * int num_elem_var number of element variables * * exit conditions - * int* elem_var_tab element variable truth table array * * revision history - * * $Id: exgvtt.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the EXODUS II element variable truth table from the database * \deprecated Use ex_get_truth_table()(exoid, EX_ELEM_BLOCK, num_elem_blk, num_elem_var, elem_var_tab) */ int ex_get_elem_var_tab (int exoid, int num_elem_blk, int num_elem_var, int *elem_var_tab) { return ex_get_truth_table(exoid, EX_ELEM_BLOCK, num_elem_blk, num_elem_var, elem_var_tab); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgean.c0000644000175000017500000000514311606020250022224 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgeat - ex_get_elem_attr_names * * entry conditions - * input parameters: * int exoid exodus file id * int elem_blk_id element block id * * exit conditions - * char* names[] ptr array of attribute names * * $Id: exgean.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the attribute names for an element block * \deprecated Use ex_get_attr_names()(exoid, EX_ELEM_BLOCK, elem_blk_id, names) instead */ int ex_get_elem_attr_names (int exoid, int elem_blk_id, char **names) { return ex_get_attr_names( exoid, EX_ELEM_BLOCK, elem_blk_id, names ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgns.c0000755000175000017500000000520711606020250022105 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgns - ex_get_node_set * * entry conditions - * input parameters: * int exoid exodus file id * int node_set_id node set id * * exit conditions - * int* node_set_node_list node list array for the node set * * revision history - * * $Id: exgns.c,v 1.1 2010-01-06 16:33:13 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the node list for a single node set * \deprecated Use ex_get_set()(exoid, EX_NODE_SET, node_set_id, node_set_node_list, NULL) */ int ex_get_node_set (int exoid, int node_set_id, int *node_set_node_list) { return ex_get_set(exoid, EX_NODE_SET, node_set_id, node_set_node_list, NULL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgeat.c0000755000175000017500000000506311606020250022236 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgeat - ex_get_elem_attr * * entry conditions - * input parameters: * int exoid exodus file id * int elem_blk_id element block id * * exit conditions - * float* attrib array of attributes * * $Id: exgeat.c,v 1.1 2010-01-06 16:33:06 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the attributes for an element block * \deprecated Use ex_get_attr()(exoid, EX_ELEM_BLOCK, elem_blk_id, attrib) instead */ int ex_get_elem_attr (int exoid, int elem_blk_id, void *attrib) { return ex_get_attr( exoid, EX_ELEM_BLOCK, elem_blk_id, attrib ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvan.c0000755000175000017500000000610411606020250022257 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvan - ex_put_var_names * * entry conditions - * input parameters: * int exoid exodus file id * char* var_type variable type: G,N, or E * int num_vars # of variables to read * char* var_names ptr array of variable names * * exit conditions - * * revision history - * * $Id: expvan.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include #include /*! * writes the names of the results variables to the database * \param exoid exodus file id * \param *var_type variable type: G,N, or E * \param num_vars # of variables to read * \param *var_names ptr array of variable names * \deprecated Use ex_put_variable_names()(exoid, obj_type, num_vars, var_names) */ int ex_put_var_names (int exoid, const char *var_type, int num_vars, char* var_names[]) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return ex_put_variable_names(exoid, obj_type, num_vars, var_names); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgssn.c0000755000175000017500000011774711606020250022305 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgssn - ex_get_side_set_node_list * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * * exit conditions - * int *side_set_node_cnt_list returned array of number of nodes for * side or face * int *side_set_node_list array of nodes * * revision history - * * $Id: exgssn.c,v 1.1 2010-01-06 16:33:37 kwleiter Exp $ * *****************************************************************************/ #include #include #include #include "exodusII.h" #include "exodusII_int.h" /*! * This routine is designed to read the Exodus II V 2.0 side set side * definition and return a ExodusI style side set node definition. */ int ex_get_side_set_node_list(int exoid, int side_set_id, int *side_set_node_cnt_list, int *side_set_node_list) { int i, j, m; int num_side_sets, num_elem_blks, num_df, ndim; int tot_num_elem = 0, tot_num_ss_elem = 0, elem_num = 0; int connect_offset, side_num, node_pos; int *elem_blk_ids, *connect = NULL; int *ss_elem_ndx, *ss_elem_node_ndx, *ss_parm_ndx; int *side_set_elem_list, *side_set_side_list; int elem_ctr, node_ctr, elem_num_pos; int num_elem_in_blk, num_nodes_per_elem, num_attr; float fdum; char *cdum, elem_type[MAX_STR_LENGTH+1]; struct elem_blk_parm *elem_blk_parms; /* side to node translation tables - These tables are used to look up the side number based on the first and second node in the side/face list. The side node order is found in the original Exodus document, SAND87-2997. The element node order is found in the ExodusII document, SAND92-2137. These tables were generated by following the right-hand rule for determining the outward normal. */ /* triangle */ static int tri_table[3][3] = { /* 1 2 3 side */ {1,2,4}, {2,3,5}, {3,1,6} /* nodes */ }; /* triangle 3d */ static int tri3_table[5][7] = { /* 1 2 side */ {1,2,3,4,5,6,7}, {3,2,1,6,5,4,7}, /* nodes */ /* 3 4 5 side */ {1,2,4,0,0,0,0}, {2,3,5,0,0,0,0}, {3,1,6,0,0,0,0} /* nodes */ }; /* quad */ static int quad_table[4][3] = { /* 1 2 3 4 side */ {1,2,5}, {2,3,6}, {3,4,7}, {4,1,8} /* nodes */ }; /* shell */ static int shell_table[6][8] = { /* 1 2 side */ {1,2,3,4,5,6,7,8}, {1,4,3,2,8,7,6,5} , /* nodes */ /* 3 4 side */ {1,2,5,0,0,0,0,0}, {2,3,6,0,0,0,0,0} , /* nodes */ /* 5 6 side */ {3,4,7,0,0,0,0,0}, {4,1,8,0,0,0,0,0} /* nodes */ }; /* tetra */ static int tetra_table[4][6] = { /* 1 2 3 4 side */ {1,2,4,5,9,8}, {2,3,4,6,10,9}, {1,4,3,8,10,7}, {1,3,2,7,6,5} /* nodes */ }; /* wedge */ static int wedge_table[5][8] = { /* 1 2 3 side */ {1,2,5,4,7,11,13,10}, {2,3,6,5,8,12,14,11}, {1,4,6,3,10,15,12,9}, /* 4 5 side */ {1,3,2,0,9,8,7,0}, {4,5,6,0,13,14,15,0} /* nodes */ }; /* hex */ static int hex_table[6][9] = { /* 1 2 side */ {1,2,6,5,9,14,17,13,26}, {2,3,7,6,10,15,18,14,25}, /* nodes */ /* 3 4 side */ {3,4,8,7,11,16,19,15,27}, {1,5,8,4,13,20,16,12,24}, /* nodes */ /* 5 6 side */ {1,4,3,2,12,11,10,9,22}, {5,6,7,8,17,18,19,20,23} /* nodes */ }; /* pyramid */ static int pyramid_table[5][8] = { /* 1 2 3 side */ {1,2,5,0,6,11,10,0}, {2,3,5,0,7,12,11,0}, {3,4,5,0,8,13,12,0}, /* nodes */ /* 4 5 side */ {1,5,4,0,10,13,9,0}, {1,4,3,2,9,8,7,6} /* nodes */ }; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ cdum = 0; /* initialize even though it is not used */ /* first check if any side sets are specified */ /* inquire how many side sets have been stored */ if ((ex_inquire(exoid, EX_INQ_SIDE_SETS, &num_side_sets, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of side sets in file id %d",exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return(EX_FATAL); } if (num_side_sets == 0) { sprintf(errmsg, "Warning: no side sets defined in file id %d",exoid); ex_err("ex_get_side_set_node_list",errmsg,EX_WARN); return(EX_WARN); } /* Lookup index of side set id in VAR_SS_IDS array */ ex_id_lkup(exoid,EX_SIDE_SET,side_set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: side set %d is NULL in file id %d", side_set_id,exoid); ex_err("ex_get_side_set_node_list",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate side set id %d in VAR_SS_IDS array in file id %d", side_set_id,exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return (EX_FATAL); } } if ((ex_inquire(exoid, EX_INQ_ELEM_BLK, &num_elem_blks, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of element blocks in file id %d",exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return(EX_FATAL); } if ((ex_inquire(exoid, EX_INQ_ELEM, &tot_num_elem, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get total number of elements in file id %d",exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return(EX_FATAL); } /* get the dimensionality of the coordinates; this is necessary to distinguish between 2d TRIs and 3d TRIs */ if ((ex_inquire(exoid, EX_INQ_DIM, &ndim, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get dimensionality in file id %d",exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); return(EX_FATAL); } /* First determine the # of elements in the side set*/ if ((ex_get_side_set_param(exoid,side_set_id,&tot_num_ss_elem,&num_df)) == -1) { sprintf(errmsg, "Error: failed to get number of elements in side set %d in file id %d", side_set_id, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return(EX_FATAL); } /* Allocate space for the side set element list */ if (!(side_set_elem_list=malloc(tot_num_ss_elem*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set element list for file id %d", exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return (EX_FATAL); } /* Allocate space for the side set side list */ if (!(side_set_side_list=malloc(tot_num_ss_elem*sizeof(int)))) { free(side_set_elem_list); exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set side list for file id %d", exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return (EX_FATAL); } if (ex_get_side_set(exoid, side_set_id, side_set_elem_list, side_set_side_list) == -1) { free(side_set_elem_list); free(side_set_side_list); sprintf(errmsg, "Error: failed to get side set %d in file id %d", side_set_id, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return (EX_FATAL); } /* Allocate space for the ss element index array */ if (!(ss_elem_ndx= malloc(tot_num_ss_elem*sizeof(int)))) { free(side_set_elem_list); free(side_set_side_list); exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set elem sort array for file id %d", exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return (EX_FATAL); } /* Sort side set element list into index array - non-destructive */ for (i=0;i= num_elem_blks) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid element number %d found in side set %d in file %d", side_set_elem_list[i], side_set_id, exoid); free(ss_parm_ndx); free(ss_elem_node_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(side_set_side_list); free(side_set_elem_list); ex_err("ex_get_side_set_node_list",errmsg,EX_MSG); return (EX_FATAL); } ss_parm_ndx[i] = j; /* assign parameter block index */ ss_elem_node_ndx[i] = node_ctr; /* assign node list index */ /* Update node_ctr (which points to next node in chain */ /* WEDGEs with 3 node sides (side 4 or 5) are special cases */ if (elem_blk_parms[j].elem_type_val == WEDGE && (side_set_side_list[i] == 4 || side_set_side_list[i] == 5)) { if (elem_blk_parms[j].num_nodes_per_elem == 6) node_ctr += 3; /* 3 node side */ else node_ctr += 6; /* 6 node side */ } /* PYRAMIDSs with 3 node sides (sides 1,2,3,4) are also special */ else if (elem_blk_parms[j].elem_type_val == PYRAMID && (side_set_side_list[i] < 5)) { if (elem_blk_parms[j].num_nodes_per_elem == 5) node_ctr += 3; /* 3 node side */ else node_ctr += 6; /* 6 node side */ } /* side numbers 3,4,5,6 for SHELLs are also special */ else if (elem_blk_parms[j].elem_type_val == SHELL && (side_set_side_list[i] > 2 )) { if (elem_blk_parms[j].num_nodes_per_elem == 4) node_ctr += 2; /* 2 node side */ else node_ctr += 3; /* 3 node side */ } /* side numbers 3,4,5 for 3d TRIs are also special */ else if (elem_blk_parms[j].elem_type_val == TRIANGLE && ndim == 3 && side_set_side_list[i] > 2 ) { if (elem_blk_parms[j].num_nodes_per_elem == 3) /* 3-node TRI */ node_ctr += 2; /* 2 node side */ else /* 6-node TRI */ node_ctr += 3; /* 3 node side */ } else /* all other element types */ node_ctr += elem_blk_parms[j].num_nodes_per_side[0]; } /* All setup, ready to go ... */ elem_ctr=0; for (j=0; j < tot_num_ss_elem; j++) { if (side_set_elem_list[ss_elem_ndx[j]] > elem_ctr) { /* release connectivity array space and get next one */ if (elem_ctr > 0) { free(connect); } /* Allocate space for the connectivity array for new element block */ if (!(connect=malloc(elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_elem_in_blk* elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_nodes_per_elem* (int)sizeof(int)))) { free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for connectivity array for file id %d", exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return (EX_FATAL); } /* get connectivity array */ if (ex_get_elem_conn( exoid, elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, connect) == -1) { free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); sprintf(errmsg, "Error: failed to allocate space for connectivity array for file id %d", exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return (EX_FATAL); } elem_ctr = elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_ctr; } /* For each side in side set, use the appropriate lookup table to determine the nodes from the connect array. */ elem_num = side_set_elem_list[ss_elem_ndx[j]]-1;/* element number 0-based*/ /* calculate the relative element number position in it's block*/ elem_num_pos = elem_num - (elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_ctr - elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_elem_in_blk); /* calculate the beginning of the node list for this element by using the ss_elem_node_ndx index into the side_sets_node_index and adding the element number position * number of nodes per elem */ num_nodes_per_elem = elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_nodes_per_elem; node_pos = ss_elem_node_ndx[ss_elem_ndx[j]]; connect_offset = num_nodes_per_elem*elem_num_pos; side_num = side_set_side_list[ss_elem_ndx[j]]-1; switch (elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_type_val) { case CIRCLE: case SPHERE: { /* Note: no side-node lookup table is used for this simple case */ side_set_node_list[node_pos] = connect[connect_offset]; side_set_node_cnt_list[ss_elem_ndx[j]] = 1; /* 1 node object */ break; } case TRUSS: case BEAM: { /* Note: no side-node lookup table is used for this simple case */ side_set_node_list[node_pos] = connect[connect_offset]; side_set_node_list[node_pos+1] = connect[connect_offset+1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 2; /* 2 node object */ if (num_nodes_per_elem > 2) { side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node object */ side_set_node_list[node_pos+2] = connect[connect_offset+2]; } break; } case TRIANGLE: { if (side_num+1 < 1 || side_num+1 > 5) /* side number range check */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid triangle edge number %d in file id %d", side_num+1, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_FATAL); } if (ndim == 2) /* 2d TRIs */ { side_set_node_list[node_pos] = connect[connect_offset+tri_table[side_num][0]-1]; side_set_node_list[node_pos+1] = connect[connect_offset+tri_table[side_num][1]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 2; /* 2 node object */ if (num_nodes_per_elem > 3) /* 6-node TRI */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node object */ side_set_node_list[node_pos+2] = connect[connect_offset+tri_table[side_num][2]-1]; } } else if (ndim == 3) /* 3d TRIs */ { side_set_node_list[node_pos] = connect[connect_offset+tri3_table[side_num][0]-1]; side_set_node_list[node_pos+1] = connect[connect_offset+tri3_table[side_num][1]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 2; /* 2 node object */ if (side_num+1 <= 2) /* 3- or 6-node face */ { if (num_nodes_per_elem == 3) /* 3-node face */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node object */ side_set_node_list[node_pos+2] = connect[connect_offset+tri3_table[side_num][2]-1]; } else /* 6-node face */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 6; /* 6 node object */ side_set_node_list[node_pos+2] = connect[connect_offset+tri3_table[side_num][2]-1]; side_set_node_list[node_pos+3] = connect[connect_offset+tri3_table[side_num][3]-1]; side_set_node_list[node_pos+4] = connect[connect_offset+tri3_table[side_num][4]-1]; side_set_node_list[node_pos+5] = connect[connect_offset+tri3_table[side_num][5]-1]; } } else /* 2- or 3-node edge */ { if (num_nodes_per_elem > 3) /* 3-node edge */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node object */ side_set_node_list[node_pos+2] = connect[connect_offset+tri3_table[side_num][2]-1]; } } } break; } case QUAD: { if (side_num+1 < 1 || side_num+1 > 4) /* side number range check */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid quad edge number %d in file id %d", side_num+1, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_FATAL); } side_set_node_list[node_pos] = connect[connect_offset+quad_table[side_num][0]-1]; side_set_node_list[node_pos+1] = connect[connect_offset+quad_table[side_num][1]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 2; /* 2 node object */ if (num_nodes_per_elem > 5) { side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node object */ side_set_node_list[node_pos+2] = connect[connect_offset+quad_table[side_num][2]-1]; } break; } case SHELL: { if (side_num+1 < 1 || side_num+1 > 6) /* side number range check */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid shell face number %d in file id %d", side_num+1, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_FATAL); } side_set_node_list[node_pos] = connect[connect_offset+shell_table[side_num][0]-1]; side_set_node_list[node_pos+1] = connect[connect_offset+shell_table[side_num][1]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 2; /* 2 node object */ if (num_nodes_per_elem > 2) /*** KLUDGE for 2D shells ***/ { if (side_num+1 <= 2) /* 4-node face */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 4; /* 4 node object */ side_set_node_list[node_pos+2] = connect[connect_offset+shell_table[side_num][2]-1]; side_set_node_list[node_pos+3] = connect[connect_offset+shell_table[side_num][3]-1]; } } if (num_nodes_per_elem == 8) { if (side_num+1 <= 2) /* 8-node face */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 8; /* 8 node object */ side_set_node_list[node_pos+4] = connect[connect_offset+shell_table[side_num][4]-1]; side_set_node_list[node_pos+5] = connect[connect_offset+shell_table[side_num][5]-1]; side_set_node_list[node_pos+6] = connect[connect_offset+shell_table[side_num][6]-1]; side_set_node_list[node_pos+7] = connect[connect_offset+shell_table[side_num][7]-1]; } else { side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node edge */ side_set_node_list[node_pos+2] = connect[connect_offset+shell_table[side_num][2]-1]; } } break; } case TETRA: { if (side_num+1 < 1 || side_num+1 > 4) /* side number range check */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid tetra face number %d in file id %d", side_num+1, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_FATAL); } side_set_node_list[node_pos] = connect[connect_offset+tetra_table[side_num][0]-1]; side_set_node_list[node_pos+1] = connect[connect_offset+tetra_table[side_num][1]-1]; side_set_node_list[node_pos+2] = connect[connect_offset+tetra_table[side_num][2]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node object */ if (num_nodes_per_elem == 8) { side_set_node_cnt_list[ss_elem_ndx[j]] = 4; /* 4 node object */ side_set_node_list[node_pos+3] = connect[connect_offset+tetra_table[side_num][3]-1]; } else if (num_nodes_per_elem > 8) { side_set_node_cnt_list[ss_elem_ndx[j]] = 6; /* 6 node object */ side_set_node_list[node_pos+3] = connect[connect_offset+tetra_table[side_num][3]-1]; side_set_node_list[node_pos+4] = connect[connect_offset+tetra_table[side_num][4]-1]; side_set_node_list[node_pos+5] = connect[connect_offset+tetra_table[side_num][5]-1]; } break; } case WEDGE: { if (side_num+1 < 1 || side_num+1 > 5) /* side number range check */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid wedge face number %d in file id %d", side_num+1, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_FATAL); } side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][0]-1]; side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][1]-1]; side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][2]-1]; if (wedge_table[side_num][3] == 0) { /* degenerate side? */ side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node side */ } else { side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][3]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 4; /* 4 node side */ } if (num_nodes_per_elem > 6) { side_set_node_cnt_list[ss_elem_ndx[j]] = 8; /* 8 node object */ side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][4]-1]; side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][5]-1]; side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][6]-1]; if (wedge_table[side_num][7] == 0) /* degenerate side? */ side_set_node_cnt_list[ss_elem_ndx[j]] = 6; /* 6 node side */ else { side_set_node_list[node_pos++] = connect[connect_offset+wedge_table[side_num][7]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 8; /* 8 node side */ } } break; } case PYRAMID: { if (side_num+1 < 1 || side_num+1 > 5) /* side number range check */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid pyramid face number %d in file id %d", side_num+1, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_FATAL); } side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][0]-1]; side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][1]-1]; side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][2]-1]; if (pyramid_table[side_num][3] == 0) { /* degenerate side? */ side_set_node_cnt_list[ss_elem_ndx[j]] = 3; /* 3 node side */ } else { side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][3]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 4; /* 4 node side */ } if (num_nodes_per_elem > 5) { side_set_node_cnt_list[ss_elem_ndx[j]] = 8; /* 8 node object */ side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][4]-1]; side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][5]-1]; side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][6]-1]; if (pyramid_table[side_num][7] == 0) /* degenerate side? */ side_set_node_cnt_list[ss_elem_ndx[j]] = 6; /* 6 node side */ else { side_set_node_list[node_pos++] = connect[connect_offset+pyramid_table[side_num][7]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 8; /* 8 node side */ } } break; } case HEX: { if (side_num+1 < 1 || side_num+1 > 6) /* side number range check */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid hex face number %d in file id %d", side_num+1, exoid); ex_err("ex_get_side_set_node_list",errmsg,exerrval); free(connect); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(ss_elem_node_ndx); free(ss_parm_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_FATAL); } side_set_node_list[node_pos] = connect[connect_offset+hex_table[side_num][0]-1]; side_set_node_list[node_pos+1] = connect[connect_offset+hex_table[side_num][1]-1]; side_set_node_list[node_pos+2] = connect[connect_offset+hex_table[side_num][2]-1]; side_set_node_list[node_pos+3] = connect[connect_offset+hex_table[side_num][3]-1]; side_set_node_cnt_list[ss_elem_ndx[j]] = 4; /* 4 node object */ if (num_nodes_per_elem > 12) /* more nodes than HEXSHELL */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 8; /* 8 node object */ side_set_node_list[node_pos+4] = connect[connect_offset+hex_table[side_num][4]-1]; side_set_node_list[node_pos+5] = connect[connect_offset+hex_table[side_num][5]-1]; side_set_node_list[node_pos+6] = connect[connect_offset+hex_table[side_num][6]-1]; side_set_node_list[node_pos+7] = connect[connect_offset+hex_table[side_num][7]-1]; } if (num_nodes_per_elem == 27) /* 27-node brick */ { side_set_node_cnt_list[ss_elem_ndx[j]] = 9; /* 9 node object */ side_set_node_list[node_pos+8] = connect[connect_offset+hex_table[side_num][8]-1]; } break; } default: { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: %s is an unsupported element type", elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_type); ex_err("ex_get_side_set_node_list",errmsg,exerrval); return(EX_FATAL); } } } /* All done: release connectivity array space, element block ids array, element block parameters array, and side set element index array */ free(connect); free(ss_parm_ndx); free(elem_blk_ids); free(elem_blk_parms); free(ss_elem_ndx); free(ss_elem_node_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgss.c0000755000175000017500000000546611606020250022121 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgss - ex_get_side_set * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * * exit conditions - * int* side_set_elem_list array of elements in side set * int* side_set_side_list array of sides in side set * * revision history - * * $Id: exgss.c,v 1.1 2010-01-06 16:33:36 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the side set element list and side set side list for a single side set * \deprecated Use ex_get_set()(exoid, EX_SIDE_SET, side_set_id, side_set_elem_list, side_set_side_list) */ int ex_get_side_set (int exoid, int side_set_id, int *side_set_elem_list, int *side_set_side_list) { return ex_get_set(exoid, EX_SIDE_SET, side_set_id, side_set_elem_list, side_set_side_list); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expoatt.c0000644000175000017500000001630111606020250022437 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expoea - ex_put_one_attr * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type object type (edge, face, elem block) * int obj_id object id (edge, face, elem block ID) * int attrib_index index of attribute to write * float* attrib array of attributes * * exit conditions - * * $Id: expoatt.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the specified attribute for a block * \param exoid exodus file id * \param obj_type object type (edge, face, elem block) * \param obj_id object id (edge, face, elem block ID) * \param attrib_index index of attribute to write * \param attrib array of attributes */ int ex_put_one_attr( int exoid, ex_entity_type obj_type, int obj_id, int attrib_index, const void *attrib ) { int status; int attrid, obj_id_ndx = 0, temp; size_t num_entries_this_obj, num_attr; size_t start[2], count[2]; ptrdiff_t stride[2]; char errmsg[MAX_ERR_LENGTH]; const char* dnumobjent; const char* dnumobjatt; const char* vattrbname; exerrval = 0; /* clear error code */ /* Determine index of obj_id in id array */ if (obj_type != EX_NODAL) { obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes allowed for NULL %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_put_one_attr",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this element block */ } else { sprintf(errmsg, "Error: no %s id %d in id array in file id %d", ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_put_one_attr",errmsg,exerrval); return (EX_FATAL); } } } switch (obj_type) { case EX_SIDE_SET: dnumobjent = DIM_NUM_SIDE_SS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx); vattrbname = VAR_SSATTRIB(obj_id_ndx); break; case EX_NODE_SET: dnumobjent = DIM_NUM_NOD_NS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx); vattrbname = VAR_NSATTRIB(obj_id_ndx); break; case EX_EDGE_SET: dnumobjent = DIM_NUM_EDGE_ES(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx); vattrbname = VAR_ESATTRIB(obj_id_ndx); break; case EX_FACE_SET: dnumobjent = DIM_NUM_FACE_FS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx); vattrbname = VAR_FSATTRIB(obj_id_ndx); break; case EX_ELEM_SET: dnumobjent = DIM_NUM_ELE_ELS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx); vattrbname = VAR_ELSATTRIB(obj_id_ndx); break; case EX_NODAL: dnumobjent = DIM_NUM_NODES; dnumobjatt = DIM_NUM_ATT_IN_NBLK; vattrbname = VAR_NATTRIB; break; case EX_EDGE_BLOCK: dnumobjent = DIM_NUM_ED_IN_EBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx); vattrbname = VAR_EATTRIB(obj_id_ndx); break; case EX_FACE_BLOCK: dnumobjent = DIM_NUM_FA_IN_FBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx); vattrbname = VAR_FATTRIB(obj_id_ndx); break; case EX_ELEM_BLOCK: dnumobjent = DIM_NUM_EL_IN_BLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx); vattrbname = VAR_ATTRIB(obj_id_ndx); break; default: sprintf(errmsg, "Error: Called with invalid obj_type %d", obj_type); ex_err("ex_put_one_attr",errmsg,exerrval); return (EX_FATAL); } /* inquire id's of previously defined dimensions */ if (ex_get_dimension(exoid, dnumobjent,"entries", &num_entries_this_obj, &temp, "ex_put_one_attr") != NC_NOERR) return EX_FATAL; if (ex_get_dimension(exoid, dnumobjatt,"attributes", &num_attr, &temp, "ex_put_one_attr") != NC_NOERR) return EX_FATAL; if (attrib_index < 1 || (size_t)attrib_index > num_attr) { exerrval = EX_FATAL; sprintf(errmsg, "Error: Invalid attribute index specified: %d. Valid range is 1 to %d for %s %d in file id %d", attrib_index, (int)num_attr, ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_put_one_attr",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_varid(exoid, vattrbname, &attrid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate attribute variable for %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_put_one_attr",errmsg,exerrval); return (EX_FATAL); } /* write out the attributes */ start[0] = 0; start[1] = attrib_index-1; count[0] = num_entries_this_obj; count[1] = 1; stride[0] = 1; stride[1] = num_attr; if (ex_comp_ws(exoid) == 4) { status = nc_put_vars_float(exoid, attrid, start, count, stride, attrib); } else { status = nc_put_vars_double(exoid, attrid, start, count, stride, attrib); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put attribute %d for %s %d in file id %d", attrib_index, ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_put_one_attr",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvv.c0000755000175000017500000000701311606020250022115 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgev - ex_get_varid_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int varid id of variable on exodus database * int num_entity number of entities for this variable * * * exit conditions - * float* var_vals array of variable values * * * revision history - * * $Id: exgvv.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the values of a single variable at one time step in the * database; assume the first time index is 1. Access based on the * passed in 'varid' * * NOTE: If used for nodal variables, it must be an ex_large_model == 1 */ int ex_get_varid_var(int exoid, int time_step, int varid, int num_entity, void *var_vals) { int status; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* read values of variable */ start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_entity; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get variable with variable id %d in file id %d", varid,exoid);/*this msg needs to be improved*/ ex_err("ex_get_varid_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgtim.c0000755000175000017500000000660611606020250022262 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgtim - ex_get_time * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * * exit conditions - * float time_value simulation time at specified step * * revision history - * * $Id: exgtim.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the time value for a specified time step; * assume the first time step is 1 */ int ex_get_time (int exoid, int time_step, void *time_value) { int status; int varid; size_t start[1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined variable */ if ((status = nc_inq_varid(exoid, VAR_WHOLE_TIME, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate time variable in file id %d", exoid); ex_err("ex_get_time",errmsg,exerrval); return (EX_FATAL); } /* read time value */ start[0] = --time_step; if (ex_comp_ws(exoid) == 4) { status = nc_get_var1_float(exoid, varid, start, time_value); } else { status = nc_get_var1_double(exoid, varid, start, time_value); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get time value in file id %d", exoid); ex_err("ex_get_time",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgcss.c0000755000175000017500000000775211606020250022264 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgcss - ex_get_concat_side_sets * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int *side_set_ids array of side set ids * int *num_elem_per_set number of elements/sides/faces per set * int *num_dist_per_set number of distribution factors per set * int *side_sets_elem_index index array of elements into elem list * int *side_sets_dist_index index array of df into df list * int *side_sets_elem_list array of elements * int *side_sets_side_list array of sides * void *side_sets_dist_fact array of distribution factors * * revision history - * * $Id: exgcss.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the side set ID's, side set element count array, side set node count * array, side set element pointers array, side set node pointers array, side * set element list, side set node list, and side set distribution factors * \deprecated Use ex_get_concat_sets()(exoid, EX_SIDE_SET, set_specs) instead */ int ex_get_concat_side_sets (int exoid, int *side_set_ids, int *num_elem_per_set, int *num_dist_per_set, int *side_sets_elem_index, int *side_sets_dist_index, int *side_sets_elem_list, int *side_sets_side_list, void *side_sets_dist_fact) { struct ex_set_specs set_specs; set_specs.sets_ids = side_set_ids; set_specs.num_entries_per_set = num_elem_per_set; set_specs.num_dist_per_set = num_dist_per_set; set_specs.sets_entry_index = side_sets_elem_index; set_specs.sets_dist_index = side_sets_dist_index; set_specs.sets_entry_list = side_sets_elem_list; set_specs.sets_extra_list = side_sets_side_list; set_specs.sets_dist_fact = side_sets_dist_fact; return ex_get_concat_sets(exoid, EX_SIDE_SET, &set_specs); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvp.c0000755000175000017500000000534611606020250022116 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvp - ex_get_var_param * * entry conditions - * input parameters: * int exoid exodus file id * char* var_type variable type G,N, or E * * exit conditions - * int* num_vars number of variables in database * * revision history - * * $Id: exgvp.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * reads the number of global, nodal, or element variables that are * stored in the database * \deprecated Use ex_get_variable_param()(exoid, obj_type, *num_vars) */ int ex_get_var_param (int exoid, const char *var_type, int *num_vars) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return (ex_get_variable_param(exoid, obj_type, num_vars)); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnam.c0000644000175000017500000001210011606020250022223 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnam - ex_get_name * * entry conditions - * input parameters: * int exoid exodus file id * const char *type entity type - M, E, S * int entity_id id of entity name to read * * exit conditions - * char* name ptr to name * * revision history - * * $Id: exgnam.c,v 1.1 2010-01-06 16:33:13 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the specified entity name from the database */ int ex_get_name (int exoid, ex_entity_type obj_type, int entity_id, char *name) { int status; int j, varid, ent_ndx; size_t num_entity; size_t start[2]; char *ptr; char errmsg[MAX_ERR_LENGTH]; char *vobj = NULL; const char *routine = "ex_get_name"; exerrval = 0; /* inquire previously defined dimensions and variables */ ent_ndx = ex_id_lkup(exoid, obj_type, entity_id); ex_get_dimension(exoid, ex_dim_num_objects(obj_type), ex_name_of_object(obj_type), &num_entity, &varid, routine); switch(obj_type) { case EX_ELEM_BLOCK: vobj = VAR_NAME_EL_BLK; break; case EX_EDGE_BLOCK: vobj = VAR_NAME_ED_BLK; break; case EX_FACE_BLOCK: vobj = VAR_NAME_FA_BLK; break; case EX_NODE_SET: vobj = VAR_NAME_NS; break; case EX_SIDE_SET: vobj = VAR_NAME_SS; break; case EX_EDGE_SET: vobj = VAR_NAME_ES; break; case EX_FACE_SET: vobj = VAR_NAME_FS; break; case EX_ELEM_SET: vobj = VAR_NAME_ELS; break; case EX_NODE_MAP: vobj = VAR_NAME_NM; break; case EX_EDGE_MAP: vobj = VAR_NAME_EDM; break; case EX_FACE_MAP: vobj = VAR_NAME_FAM; break; case EX_ELEM_MAP: vobj = VAR_NAME_EM; break; default: /* invalid variable type */ exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid type specified in file id %d", exoid); ex_err(routine,errmsg,exerrval); return(EX_FATAL); } if ((status = nc_inq_varid(exoid, vobj, &varid)) == NC_NOERR) { /* If this is a null entity, then 'ent_ndx' will be negative. * We don't care in this routine, so make it positive and continue... */ if (ent_ndx < 0) ent_ndx = -ent_ndx; /* read the name */ start[0] = ent_ndx-1; start[1] = 0; j = 0; ptr = name; if ((status = nc_get_var1_text(exoid, varid, start, ptr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get entity name for id %d in file id %d", ent_ndx, exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } while ((*ptr++ != '\0') && (j < MAX_STR_LENGTH)) { start[1] = ++j; if ((status = nc_get_var1_text(exoid, varid, start, ptr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get name in file id %d", exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } } --ptr; if (ptr > name) { while (--ptr >= name && *ptr == ' '); /* get rid of trailing blanks */ } *(++ptr) = '\0'; } else { /* Name variable does not exist on the database; probably since this is an * older version of the database. Return an empty array... */ name[0] = '\0'; } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgattp.c0000644000175000017500000001103111606020250022422 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expmp - ex_get_attr_param * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type block/set type (node, edge, face, elem) * int obj_id block/set id (ignored for NODAL) * int num_attrs number of attributes * * exit conditions - * * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * retrieves the number of attributes. */ int ex_get_attr_param (int exoid, ex_entity_type obj_type, int obj_id, int* num_attrs) { int status; int dimid; char errmsg[MAX_ERR_LENGTH]; const char *dnumobjatt; int obj_id_ndx; size_t lnum_attr_per_entry; /* Determine index of obj_id in vobjids array */ if (obj_type == EX_NODAL) obj_id_ndx = 0; else { obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { *num_attrs = 0; return (EX_NOERR); } else { sprintf(errmsg, "Warning: failed to locate %s id %d in id array in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_attr_param",errmsg,exerrval); return (EX_WARN); } } } switch (obj_type) { case EX_SIDE_SET: dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx); break; case EX_NODE_SET: dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx); break; case EX_EDGE_SET: dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx); break; case EX_FACE_SET: dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx); break; case EX_ELEM_SET: dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx); break; case EX_NODAL: dnumobjatt = DIM_NUM_ATT_IN_NBLK; break; case EX_EDGE_BLOCK: dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx); break; case EX_FACE_BLOCK: dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx); break; case EX_ELEM_BLOCK: dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Bad block type (%d) specified for file id %d", obj_type, exoid ); ex_err("ex_get_attr_param",errmsg,exerrval); return (EX_FATAL); } exerrval = 0; /* clear error code */ if ((status = nc_inq_dimid(exoid, dnumobjatt, &dimid)) != NC_NOERR) { /* dimension is undefined */ *num_attrs = 0; } else { if ((status = nc_inq_dimlen(exoid, dimid, &lnum_attr_per_entry)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of attributes in %s %d in file id %d", ex_name_of_object(obj_type),obj_id, exoid); ex_err("ex_get_attr_param",errmsg, exerrval); return(EX_FATAL); } *num_attrs = lnum_attr_per_entry; } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgcon.c0000755000175000017500000001113111606020250022235 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgcon - ex_get_coord_names * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * char* coord_names[] ptr array of coord names * * revision history - * * $Id: exgcon.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the names (#MAX_STR_LENGTH characters in length) of the * coordinate arrays from the database. Memory must be allocated for * the character strings before this function is invoked. * \param exoid exodus file id * \param[out] coord_names Returned pointer to a vector containing * 'num_dim' names of the nodal coordinate arrays. */ int ex_get_coord_names (int exoid, char **coord_names) { int status; size_t i; int j, ndimdim, varid; size_t num_dim, start[2]; char *ptr; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* inquire previously defined dimensions and variables */ if ((status = nc_inq_dimid(exoid, DIM_NUM_DIM, &ndimdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of dimensions in file id %d", exoid); ex_err("ex_get_coord_names",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, ndimdim, &num_dim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of dimensions in file id %d", exoid); ex_err("ex_get_coord_names",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_varid(exoid, VAR_NAME_COOR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: failed to locate coordinate names in file id %d", exoid); ex_err("ex_get_coord_names",errmsg,exerrval); return (EX_WARN); } /* read the coordinate names */ for (i=0; i coord_names[i]) { /* get rid of trailing blanks */ while (--ptr >= coord_names[i] && *ptr == ' '); } *(++ptr) = '\0'; } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnnm.c0000755000175000017500000000455411606020250022261 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnnm - ex_get_node_num_map * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int* node_map node numbering map array * * revision history - * * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the node numbering map from the database */ int ex_get_node_num_map (int exoid, int *node_map) { return ex_get_id_map(exoid, EX_NODE_MAP, node_map); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgatm.c0000755000175000017500000000675511606020250022257 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgatm - get all time values * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * float* time_values array of simulation time values * * revision history - * * $Id: exgatm.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the time values for all time steps. Memory must be allocated * for the time values array before this function is invoked. The * storage requirements (equal to the number of time steps) can be * determined by using the ex_inquire() routine. * \param exoid exodus file id * \param[out] time_values Returned array of time values at all time steps. */ int ex_get_all_times (int exoid, void *time_values) { int varid; int status; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; if ((status = nc_inq_varid(exoid, VAR_WHOLE_TIME, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to locate time variable %s in file id %d", VAR_WHOLE_TIME, exoid); ex_err("ex_get_all_times",errmsg,exerrval); return(EX_FATAL); } /*read time values */ if (ex_comp_ws(exoid) == 4) { status = nc_get_var_float(exoid, varid, time_values); } else { status = nc_get_var_double(exoid, varid, time_values); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get time values from file id %d", exoid); ex_err("ex_get_all_times",errmsg,exerrval); return(EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exupda.c0000755000175000017500000000512611606020250022247 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exupda - ex_update * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * * $Id: exupda.c,v 1.1 2010-01-06 16:33:51 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * updates an opened EXODUS II file (or EXODUS II history file) * \param exoid exodus file id */ int ex_update (int exoid) { char errmsg[MAX_ERR_LENGTH]; int status; exerrval = 0; /* clear error code */ if ((status = nc_sync(exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to update file id %d", exoid); ex_err("ex_update",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expcns.c0000755000175000017500000001061411606020250022257 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expcns - ex_put_concat_node_sets * * entry conditions - * input parameters: * int exoid exodus file id * int* node_set_ids array of node set ids * int* num_nodes_per_set array of number of nodes per set * int* num_dist_per_set array of number of dist fact per set * ----------pass in NULL for remaining args if just want to set params ------------- * int* node_sets_node_index array of set indices into node list * int* node_sets_df_index array of set indices into dist fact list * int* node_set_node_list array of node list #'s for node set * void* node_set_dist_fact array of dist factors for node set * * exit conditions - * * revision history - * * $Id: expcns.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the node set ID's, node set count array, node set pointers array, * and node set node list for all of the node sets * \param exoid exodus file id * \param node_set_ids array of node set ids * \param num_nodes_per_set array of number of nodes per set * \param num_dist_per_set array of number of dist fact per set * \param node_sets_node_index array of set indices into node list * \param node_sets_df_index array of set indices into dist fact list * \param node_sets_node_list array of node list #'s for node set * \param node_sets_dist_fact array of dist factors for node set * \deprecated Use ex_put_concat_sets()(exoid, EX_NODE_SET, &set_specs) */ int ex_put_concat_node_sets (int exoid, int *node_set_ids, int *num_nodes_per_set, int *num_dist_per_set, int *node_sets_node_index, int *node_sets_df_index, int *node_sets_node_list, void *node_sets_dist_fact) { struct ex_set_specs set_specs; set_specs.sets_ids = node_set_ids; set_specs.num_entries_per_set = num_nodes_per_set; set_specs.num_dist_per_set = num_dist_per_set; set_specs.sets_entry_index = node_sets_node_index; set_specs.sets_dist_index = node_sets_df_index; set_specs.sets_entry_list = node_sets_node_list; set_specs.sets_extra_list = NULL; set_specs.sets_dist_fact = node_sets_dist_fact; return ex_put_concat_sets(exoid, EX_NODE_SET, &set_specs); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exppa.c0000755000175000017500000002233211606020250022074 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exppa - ex_put_prop_array: write object property array * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type type of object (element block, node * set or side set) * char* prop_name name of the property for which the * values will be stored * int* values array of property values * * exit conditions - * * revision history - * * $Id: exppa.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include #include /* for free() */ /*! * writes an array of object properties * \param exoid exodus file id * \param obj_type type of object (element block, node set or side set) * \param prop_name name of the property for which the values will be stored * \param values array of property values */ int ex_put_prop_array (int exoid, ex_entity_type obj_type, const char *prop_name, const int *values) { int oldfill, temp; int num_props, i, propid, dimid, dims[1], status; int found = FALSE; size_t num_obj; char name[MAX_VAR_NAME_LENGTH+1]; char tmpstr[MAX_STR_LENGTH+1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* check if property has already been created */ num_props = ex_get_num_props(exoid, obj_type); /* inquire id of previously defined dimension (number of objects) */ status = ex_get_dimension(exoid, ex_dim_num_objects(obj_type), ex_name_of_object(obj_type), &num_obj, &dimid, "ex_put_prop_array"); if (status != NC_NOERR) return status; for (i=1; i<=num_props; i++) { switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(i)); break; case EX_FACE_BLOCK: strcpy (name, VAR_FA_PROP(i)); break; case EX_EDGE_BLOCK: strcpy (name, VAR_ED_PROP(i)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(i)); break; case EX_EDGE_SET: strcpy (name, VAR_ES_PROP(i)); break; case EX_FACE_SET: strcpy (name, VAR_FS_PROP(i)); break; case EX_ELEM_SET: strcpy (name, VAR_ELS_PROP(i)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(i)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(i)); break; case EX_FACE_MAP: strcpy (name, VAR_FAM_PROP(i)); break; case EX_EDGE_MAP: strcpy (name, VAR_EDM_PROP(i)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(i)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return(EX_FATAL); } if ((status = nc_inq_varid(exoid, name, &propid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get property array id in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } /* compare stored attribute name with passed property name */ memset(tmpstr, 0, MAX_STR_LENGTH+1); if ((status = nc_get_att_text(exoid, propid, ATT_PROP_NAME, tmpstr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get property name in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } if (strcmp(tmpstr, prop_name) == 0) { found = TRUE; break; } } /* if property array has not been created, create it */ if (!found) { /* put netcdf file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } /* create a variable with a name xx_prop#, where # is the new number */ /* of properties */ switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(num_props+1)); break; case EX_FACE_BLOCK: strcpy (name, VAR_FA_PROP(num_props+1)); break; case EX_EDGE_BLOCK: strcpy (name, VAR_ED_PROP(num_props+1)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(num_props+1)); break; case EX_EDGE_SET: strcpy (name, VAR_ES_PROP(num_props+1)); break; case EX_FACE_SET: strcpy (name, VAR_FS_PROP(num_props+1)); break; case EX_ELEM_SET: strcpy (name, VAR_ELS_PROP(num_props+1)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(num_props+1)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(num_props+1)); break; case EX_FACE_MAP: strcpy (name, VAR_FAM_PROP(num_props+1)); break; case EX_EDGE_MAP: strcpy (name, VAR_EDM_PROP(num_props+1)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(num_props+1)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop_array",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } dims[0] = dimid; nc_set_fill(exoid, NC_FILL, &oldfill); /* fill with zeros per routine spec */ if ((status = nc_def_var(exoid, name, NC_INT, 1, dims, &propid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create property array variable in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } nc_set_fill(exoid, oldfill, &temp); /* default: nofill */ /* store property name as attribute of property array variable */ if ((status = nc_put_att_text(exoid, propid, ATT_PROP_NAME, strlen(prop_name)+1, prop_name)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store property name %s in file id %d", prop_name,exoid); ex_err("ex_put_prop_array",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to leave define mode in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } } /* put num_obj values in property array */ status = nc_put_var_int(exoid, propid, values); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store property values in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: nc_set_fill(exoid, oldfill, &temp); /* default: nofill */ if (nc_enddef (exoid) != NC_NOERR) { /* exit define mode */ sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgatn.c0000644000175000017500000001605411606020250022246 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgeat - ex_get_attr_names * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type object type (edge/face/elem block) * int obj_id object id (edge/face/elem block id) * * exit conditions - * char* names[] ptr array of attribute names * * revision history - * * $Id: exgatn.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the attribute names for an element block */ int ex_get_attr_names( int exoid, ex_entity_type obj_type, int obj_id, char **names) { int status; int varid, numattrdim, obj_id_ndx = 0; size_t i, num_attr, start[2]; char *ptr; char errmsg[MAX_ERR_LENGTH]; int j; const char* dnumobjatt; const char* vattrbname; exerrval = 0; /* clear error code */ /* Determine index of obj_id in vobjids array */ if (obj_type != EX_NODAL) { obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes found for NULL %s %d in file id %d", ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_get_attr_names",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this object */ } else { sprintf(errmsg, "Warning: failed to locate %s id %d in id array in file id %d", ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_get_attr_names",errmsg,exerrval); return (EX_WARN); } } } switch (obj_type) { case EX_NODE_SET: dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx); vattrbname = VAR_NAME_NSATTRIB(obj_id_ndx); break; case EX_SIDE_SET: dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx); vattrbname = VAR_NAME_SSATTRIB(obj_id_ndx); break; case EX_EDGE_SET: dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx); vattrbname = VAR_NAME_ESATTRIB(obj_id_ndx); break; case EX_FACE_SET: dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx); vattrbname = VAR_NAME_FSATTRIB(obj_id_ndx); break; case EX_ELEM_SET: dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx); vattrbname = VAR_NAME_ELSATTRIB(obj_id_ndx); break; case EX_NODAL: dnumobjatt = DIM_NUM_ATT_IN_NBLK; vattrbname = VAR_NAME_NATTRIB; break; case EX_EDGE_BLOCK: dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx); vattrbname = VAR_NAME_EATTRIB(obj_id_ndx); break; case EX_FACE_BLOCK: dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx); vattrbname = VAR_NAME_FATTRIB(obj_id_ndx); break; case EX_ELEM_BLOCK: dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx); vattrbname = VAR_NAME_ATTRIB(obj_id_ndx); break; default: sprintf(errmsg, "Error: called with invalid object type %d", obj_type); ex_err("ex_get_attr_names",errmsg,exerrval); return (EX_FATAL); break; } /* inquire id's of previously defined dimensions */ if ((status = nc_inq_dimid(exoid, dnumobjatt, &numattrdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no attributes found for %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_attr_names",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this object */ } if ((status = nc_inq_dimlen(exoid, numattrdim, &num_attr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of attributes for %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_attr_names",errmsg,exerrval); return (EX_FATAL); } /* It is OK if we don't find the attribute names since they were added at version 4.26; earlier databases won't have the names. */ status = nc_inq_varid(exoid, vattrbname, &varid); /* read in the attributes */ if (status == NC_NOERR) { /* read the names */ for (i=0; i < num_attr; i++) { start[0] = i; start[1] = 0; j = 0; ptr = names[i]; if ((status = nc_get_var1_text (exoid, varid, start, ptr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get names for %s %d in file id %d", ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_get_attr_names",errmsg,exerrval); return (EX_FATAL); } while ((*ptr++ != '\0') && (j < MAX_STR_LENGTH)) { start[1] = ++j; if ((status = nc_get_var1_text(exoid, varid, start, ptr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get names for %s %d in file id %d", ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_get_attr_names",errmsg,exerrval); return (EX_FATAL); } } --ptr; if (ptr > names[i]) { /* get rid of trailing blanks */ while (--ptr >= names[i] && *ptr == ' '); } *(++ptr) = '\0'; } } else { /* Names variable does not exist on the database; probably since this is an * older version of the database. Return an empty array... */ for (i=0; i #include #include #include "exodusII.h" #include "exodusII_int.h" /* * This routine is designed to read the Exodus II V 2.0 side set side * definition and return the length of a ExodusI style side set node list. */ int ex_get_side_set_node_list_len(int exoid, int side_set_id, int *side_set_node_list_len) { int i, j, m; int num_side_sets, num_elem_blks, num_df, ndim; int tot_num_elem = 0, tot_num_ss_elem = 0; int *elem_blk_ids; int *ss_elem_ndx; int *side_set_elem_list, *side_set_side_list; int elem_ctr; int num_elem_in_blk, num_nodes_per_elem, num_attr; float fdum; char *cdum, elem_type[MAX_STR_LENGTH+1]; struct elem_blk_parm { char elem_type[MAX_STR_LENGTH+1]; int elem_blk_id; int num_elem_in_blk; int num_nodes_per_elem; int num_nodes_per_side; int num_attr; int elem_ctr; int elem_type_val; } *elem_blk_parms; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ cdum = 0; /* initialize even though it is not used */ *side_set_node_list_len = 0; /* default value */ /* first check if any side sets are specified */ /* inquire how many side sets have been stored */ if ((ex_inquire(exoid, EX_INQ_SIDE_SETS, &num_side_sets, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of side sets in file id %d",exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return(EX_FATAL); } if (num_side_sets == 0) { sprintf(errmsg, "Warning: no side sets defined in file id %d",exoid); ex_err("ex_get_side_set_node_list_len",errmsg,EX_WARN); return(EX_WARN); } if ((ex_inquire(exoid, EX_INQ_ELEM_BLK, &num_elem_blks, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of element blocks in file id %d",exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return(EX_FATAL); } if ((ex_inquire(exoid, EX_INQ_ELEM, &tot_num_elem, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get total number of elements in file id %d",exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return(EX_FATAL); } /* get the dimensionality of the coordinates; this is necessary to distinguish between 2d TRIs and 3d TRIs */ if ((ex_inquire(exoid, EX_INQ_DIM, &ndim, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get dimensionality in file id %d",exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return(EX_FATAL); } /* First determine the # of elements in the side set*/ if ((ex_get_side_set_param(exoid,side_set_id,&tot_num_ss_elem,&num_df)) == -1) { sprintf(errmsg, "Error: failed to get number of elements in side set %d in file id %d", side_set_id, exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return(EX_FATAL); } if (tot_num_ss_elem == 0) /* NULL side set? */ return (EX_NOERR); /* return zero */ /* Allocate space for the side set element list */ if (!(side_set_elem_list=malloc(tot_num_ss_elem*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set element list for file id %d", exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return (EX_FATAL); } /* Allocate space for the side set side list */ if (!(side_set_side_list=malloc(tot_num_ss_elem*sizeof(int)))) { free(side_set_elem_list); exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set side list for file id %d", exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return (EX_FATAL); } if (ex_get_side_set(exoid, side_set_id, side_set_elem_list, side_set_side_list) == -1) { free(side_set_elem_list); free(side_set_side_list); sprintf(errmsg, "Error: failed to get side set %d in file id %d", side_set_id, exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return (EX_FATAL); } /* Allocate space for the ss element index array */ if (!(ss_elem_ndx=malloc(tot_num_ss_elem*sizeof(int)))) { free(side_set_elem_list); free(side_set_side_list); exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for side set elem sort array for file id %d", exoid); ex_err("ex_get_side_set_node_list_len",errmsg,exerrval); return (EX_FATAL); } /* Sort side set element list into index array - non-destructive */ for (i=0;i= num_elem_blks) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid element number %d found in side set %d in file %d", side_set_elem_list[i], side_set_id, exoid); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(side_set_side_list); free(side_set_elem_list); ex_err("ex_get_side_set_node_list_len",errmsg,EX_MSG); return (EX_FATAL); } /* Update *side_set_node_list_len (which points to next node in chain */ /* WEDGEs with 3 node sides (side 4 or 5) are special cases */ if (elem_blk_parms[j].elem_type_val == WEDGE && (side_set_side_list[i] == 4 || side_set_side_list[i] == 5)) { if (elem_blk_parms[j].num_nodes_per_elem == 6) *side_set_node_list_len += 3; /* 3 node side */ else *side_set_node_list_len += 6; /* 6 node side */ } /* PYRAMIDSs with 3 node sides (sides 1,2,3,4) are also special */ else if (elem_blk_parms[j].elem_type_val == PYRAMID && (side_set_side_list[i] < 5)) { if (elem_blk_parms[j].num_nodes_per_elem == 5) *side_set_node_list_len += 3; /* 3 node side */ else *side_set_node_list_len += 6; /* 6 node side */ } /* side numbers 3,4,5,6 for SHELLs are also special */ else if (elem_blk_parms[j].elem_type_val == SHELL && (side_set_side_list[i] > 2 )) { if (elem_blk_parms[j].num_nodes_per_elem == 4) *side_set_node_list_len += 2; /* 2 node side */ else *side_set_node_list_len += 3; /* 3 node side */ } /* sides 3, 4, and 5 of 3d TRIs are special cases */ else if (elem_blk_parms[j].elem_type_val == TRIANGLE && ndim == 3 && side_set_side_list[i] > 2 ) { if (elem_blk_parms[j].num_nodes_per_elem == 3) /* 3-node TRI */ *side_set_node_list_len += 2; /* 2 node side */ else /* 6-node TRI */ *side_set_node_list_len += 3; /* 3 node side */ } else if (elem_blk_parms[j].elem_type_val == UNK) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: %s in elem block %d is an unsupported element type", elem_blk_parms[i].elem_type, elem_blk_parms[i].elem_blk_id); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); free(side_set_side_list); free(side_set_elem_list); ex_err("ex_get_side_set_node_list_len",errmsg,EX_MSG); return (EX_FATAL); } else /* all other element types */ *side_set_node_list_len += elem_blk_parms[j].num_nodes_per_side; } /* All done: release element block ids array, element block parameters array, and side set element index array */ free(elem_blk_ids); free(elem_blk_parms); free(ss_elem_ndx); free(side_set_side_list); free(side_set_elem_list); return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgpem.c0000644000175000017500000001247611606020250022251 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgpem - ex_get_partial_elem_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_id element map id * int ent_start first entry in map * int ent_count number of entries in map * * exit conditions - * int* elem_map element map * * revision history - * * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the element map with specified ID */ int ex_get_partial_elem_map (int exoid, int map_id, int ent_start, int ent_count, int *elem_map) { int dimid, var_id, id_ndx, status; size_t num_elem, start[1], count[1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* See if file contains any elements...*/ if (nc_inq_dimid (exoid, DIM_NUM_ELEM, &dimid) != NC_NOERR) { return (EX_NOERR); } if ((status = nc_inq_dimlen(exoid, dimid, &num_elem)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of elements in file id %d", exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* Check input parameters for a valid range of numbers */ if (ent_start <= 0 || ent_start > (int)num_elem) { exerrval = EX_FATAL; sprintf(errmsg, "Error: start count is invalid in file id %d", exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } if (ent_count < 0) { exerrval = EX_FATAL; sprintf(errmsg, "Error: Invalid count value in file id %d", exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } if (ent_start+ent_count-1 > (int)num_elem) { exerrval = EX_FATAL; sprintf(errmsg, "Error: start+count-1 is larger than element count in file id %d", exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* first check if any element maps have been defined */ if ((status = nc_inq_dimid (exoid, DIM_NUM_EM, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no element maps defined in file id %d", exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_WARN); } /* Lookup index of element map id property array */ id_ndx = ex_id_lkup(exoid,EX_ELEM_MAP,map_id); if (exerrval != 0) { sprintf(errmsg, "Error: failed to locate element map id %d in %s in file id %d", map_id,VAR_EM_PROP(1),exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* inquire id's of previously defined dimensions and variables */ if ((status = nc_inq_varid(exoid, VAR_ELEM_MAP(id_ndx), &var_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate element map %d in file id %d", map_id,exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* read in the element map */ start[0] = ent_start-1; count[0] = ent_count; status = nc_get_vara_int(exoid, var_id, start, count, elem_map); if (status == -1) { exerrval = status; sprintf(errmsg, "Error: failed to get element map in file id %d", exoid); ex_err("ex_get_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvv.c0000755000175000017500000000746411606020250022140 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnv - ex_put_varid_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step whole time step number * int varid id of variable on exodus database * int num_entity number of entities for this variable * float* var_vals array of nodal variable values * * exit conditions - * * revision history - * * $Id: expvv.c,v 1.1 2010-01-06 16:33:51 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of a single variable at one time step in the * database; assume the first time index is 1. Access based on the * passed in 'varid' * * NOTE: If used for nodal variables, it must be an ex_large_model == 1 * \param exoid int exodus file id * \param time_step int whole time step number * \param varid int id of variable on exodus database * \param num_entity int number of entities for this variable * \param var_vals float* array of nodal variable values */ int ex_put_varid_var(int exoid, int time_step, int varid, int num_entity, const void *var_vals) { size_t start[2], count[2]; int status; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_entity; if (ex_comp_ws(exoid) == 4) { status = nc_put_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_put_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store variables with varid %d in file id %d", varid, exoid); ex_err("ex_put_varid_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvnm.c0000755000175000017500000000614111606020250022274 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvnm - ex_put_var_name * * entry conditions - * input parameters: * int exoid exodus file id * char* var_type variable type: G,N, or E * int var_num variable number name to write 1..num_var * char* var_name ptr of variable name * * exit conditions - * * revision history - * * $Id: expvnm.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include #include /*! * writes the name of a particular results variable to the database * \param exoid exodus file id * \param *var_type variable type: G,N, or E * \param var_num variable number name to write 1..num_var * \param *var_name ptr of variable name * \deprecated use ex_put_variable_name()(exoid, obj_type, var_num, *var_name) */ int ex_put_var_name (int exoid, const char *var_type, int var_num, const char *var_name) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return ex_put_variable_name(exoid, obj_type, var_num, var_name); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgatt.c0000644000175000017500000001201211606020250022242 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgatt - ex_get_attr * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type object type (edge/face/element block) * int obj_id object id (edge id, face id, elem id) * * exit conditions - * float* attrib array of attributes * * revision history - * * $Id: exgatt.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the attributes for an edge, face, or element block */ int ex_get_attr( int exoid, ex_entity_type obj_type, int obj_id, void* attrib ) { int status; int attrid, obj_id_ndx; char errmsg[MAX_ERR_LENGTH]; const char* vattrbname; exerrval = 0; /* clear error code */ /* Determine index of obj_id in vobjids array */ if (obj_type == EX_NODAL) obj_id_ndx = 0; else { obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes found for NULL %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_attr",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this object */ } else { sprintf(errmsg, "Warning: failed to locate %s id %d in id array in file id %d", ex_name_of_object(obj_type),obj_id, exoid); ex_err("ex_get_attr",errmsg,exerrval); return (EX_WARN); } } } switch (obj_type) { case EX_SIDE_SET: vattrbname = VAR_SSATTRIB(obj_id_ndx); break; case EX_NODE_SET: vattrbname = VAR_NSATTRIB(obj_id_ndx); break; case EX_EDGE_SET: vattrbname = VAR_ESATTRIB(obj_id_ndx); break; case EX_FACE_SET: vattrbname = VAR_FSATTRIB(obj_id_ndx); break; case EX_ELEM_SET: vattrbname = VAR_ELSATTRIB(obj_id_ndx); break; case EX_NODAL: vattrbname = VAR_NATTRIB; break; case EX_EDGE_BLOCK: vattrbname = VAR_EATTRIB(obj_id_ndx); break; case EX_FACE_BLOCK: vattrbname = VAR_FATTRIB(obj_id_ndx); break; case EX_ELEM_BLOCK: vattrbname = VAR_ATTRIB(obj_id_ndx); break; default: sprintf(errmsg, "Error: called with invalid obj_type %d", obj_type); ex_err("ex_get_attr",errmsg,exerrval); return (EX_WARN); break; } /* inquire id's of previously defined dimensions */ if ((status = nc_inq_varid(exoid, vattrbname, &attrid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate attributes for %s %d in file id %d", ex_name_of_object(obj_type), obj_id,exoid); ex_err("ex_get_attr",errmsg,exerrval); return (EX_FATAL); } /* read in the attributes */ if (ex_comp_ws(exoid) == 4) { status = nc_get_var_float(exoid, attrid, attrib); } else { status = nc_get_var_double(exoid, attrid, attrib); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get attributes for %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_attr",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/CVS/0000755000175000017500000000000011606020250021241 5ustar amckinstryamckinstryxdmf-2.1.dfsg.1/Utilities/vtkexodus2/CVS/Entries0000644000175000017500000001525411606020250022604 0ustar amckinstryamckinstry/.NoDartCoverage/1.1/Wed Jan 6 16:32:59 2010// /CMakeLists.txt/1.1/Wed Jan 6 16:33:02 2010// /COPYRIGHT/1.1/Wed Jan 6 16:33:04 2010// /ex_conv.c/1.1/Wed Jan 6 16:33:04 2010// /ex_utils.c/1.1/Wed Jan 6 16:33:04 2010// /exclos.c/1.1/Wed Jan 6 16:33:04 2010// /excn2s.c/1.1/Wed Jan 6 16:33:05 2010// /excopy.c/1.1/Wed Jan 6 16:33:05 2010// /excre.c/1.1/Wed Jan 6 16:33:05 2010// /exerr.c/1.1/Wed Jan 6 16:33:05 2010// /exgatm.c/1.1/Wed Jan 6 16:33:05 2010// /exgatn.c/1.1/Wed Jan 6 16:33:05 2010// /exgatt.c/1.1/Wed Jan 6 16:33:05 2010// /exgattp.c/1.1/Wed Jan 6 16:33:05 2010// /exgblk.c/1.1/Wed Jan 6 16:33:05 2010// /exgcns.c/1.1/Wed Jan 6 16:33:05 2010// /exgcon.c/1.1/Wed Jan 6 16:33:05 2010// /exgconn.c/1.1/Wed Jan 6 16:33:05 2010// /exgcor.c/1.1/Wed Jan 6 16:33:05 2010// /exgcset.c/1.1/Wed Jan 6 16:33:05 2010// /exgcss.c/1.1/Wed Jan 6 16:33:05 2010// /exgean.c/1.1/Wed Jan 6 16:33:05 2010// /exgeat.c/1.1/Wed Jan 6 16:33:06 2010// /exgebi.c/1.1/Wed Jan 6 16:33:06 2010// /exgelb.c/1.1/Wed Jan 6 16:33:07 2010// /exgelc.c/1.1/Wed Jan 6 16:33:07 2010// /exgem.c/1.1/Wed Jan 6 16:33:07 2010// /exgenm.c/1.1/Wed Jan 6 16:33:07 2010// /exgev.c/1.1/Wed Jan 6 16:33:07 2010// /exgevid.c/1.1/Wed Jan 6 16:33:07 2010// /exgevt.c/1.1/Wed Jan 6 16:33:08 2010// /exgfrm.c/1.1/Wed Jan 6 16:33:10 2010// /exggv.c/1.1/Wed Jan 6 16:33:11 2010// /exggvt.c/1.1/Wed Jan 6 16:33:12 2010// /exgidm.c/1.1/Wed Jan 6 16:33:12 2010// /exgids.c/1.1/Wed Jan 6 16:33:12 2010// /exginf.c/1.1/Wed Jan 6 16:33:12 2010// /exgini.c/1.1/Wed Jan 6 16:33:12 2010// /exginix.c/1.1/Wed Jan 6 16:33:12 2010// /exgmap.c/1.1/Wed Jan 6 16:33:12 2010// /exgmp.c/1.1/Wed Jan 6 16:33:13 2010// /exgnam.c/1.1/Wed Jan 6 16:33:13 2010// /exgnams.c/1.1/Wed Jan 6 16:33:13 2010// /exgnm.c/1.1/Wed Jan 6 16:33:13 2010// /exgnmap.c/1.1/Wed Jan 6 16:33:13 2010// /exgnnm.c/1.1/Wed Jan 6 16:33:13 2010// /exgnp.c/1.1/Wed Jan 6 16:33:13 2010// /exgns.c/1.1/Wed Jan 6 16:33:13 2010// /exgnsd.c/1.1/Wed Jan 6 16:33:13 2010// /exgnsi.c/1.1/Wed Jan 6 16:33:14 2010// /exgnstt.c/1.1/Wed Jan 6 16:33:18 2010// /exgnsv.c/1.1/Wed Jan 6 16:33:19 2010// /exgnsvid.c/1.1/Wed Jan 6 16:33:19 2010// /exgnv.c/1.1/Wed Jan 6 16:33:20 2010// /exgnvid.c/1.1/Wed Jan 6 16:33:23 2010// /exgnvt.c/1.1/Wed Jan 6 16:33:27 2010// /exgnvv.c/1.1/Wed Jan 6 16:33:29 2010// /exgoatt.c/1.1/Wed Jan 6 16:33:30 2010// /exgoea.c/1.1/Wed Jan 6 16:33:30 2010// /exgotv.c/1.1/Wed Jan 6 16:33:31 2010// /exgp.c/1.1/Wed Jan 6 16:33:31 2010// /exgpa.c/1.1/Wed Jan 6 16:33:32 2010// /exgpem.c/1.1/Wed Jan 6 16:33:32 2010// /exgpn.c/1.1/Wed Jan 6 16:33:32 2010// /exgqa.c/1.1/Wed Jan 6 16:33:32 2010// /exgset.c/1.1/Wed Jan 6 16:33:33 2010// /exgsetd.c/1.1/Wed Jan 6 16:33:35 2010// /exgsetp.c/1.1/Wed Jan 6 16:33:36 2010// /exgsnl.c/1.1/Wed Jan 6 16:33:36 2010// /exgsp.c/1.1/Wed Jan 6 16:33:36 2010// /exgss.c/1.1/Wed Jan 6 16:33:36 2010// /exgssc.c/1.1/Wed Jan 6 16:33:36 2010// /exgssd.c/1.1/Wed Jan 6 16:33:37 2010// /exgssi.c/1.1/Wed Jan 6 16:33:37 2010// /exgssn.c/1.1/Wed Jan 6 16:33:37 2010// /exgsstt.c/1.1/Wed Jan 6 16:33:37 2010// /exgssv.c/1.1/Wed Jan 6 16:33:38 2010// /exgssvid.c/1.1/Wed Jan 6 16:33:38 2010// /exgtim.c/1.1/Wed Jan 6 16:33:38 2010// /exgtt.c/1.1/Wed Jan 6 16:33:38 2010// /exgvan.c/1.1/Wed Jan 6 16:33:38 2010// /exgvar.c/1.1/Wed Jan 6 16:33:38 2010// /exgvarnam.c/1.1/Wed Jan 6 16:33:38 2010// /exgvarnams.c/1.1/Wed Jan 6 16:33:38 2010// /exgvarparam.c/1.1/Wed Jan 6 16:33:38 2010// /exgvart.c/1.1/Wed Jan 6 16:33:38 2010// /exgvartab.c/1.1/Wed Jan 6 16:33:38 2010// /exgvid.c/1.1/Wed Jan 6 16:33:38 2010// /exgvnm.c/1.1/Wed Jan 6 16:33:38 2010// /exgvp.c/1.1/Wed Jan 6 16:33:38 2010// /exgvtt.c/1.1/Wed Jan 6 16:33:38 2010// /exgvv.c/1.1/Wed Jan 6 16:33:39 2010// /exinq.c/1.1/Wed Jan 6 16:33:39 2010// /exopen.c/1.1/Wed Jan 6 16:33:39 2010// /exopts.c/1.1/Wed Jan 6 16:33:39 2010// /expatn.c/1.1/Wed Jan 6 16:33:39 2010// /expatt.c/1.1/Wed Jan 6 16:33:39 2010// /expattp.c/1.1/Wed Jan 6 16:33:39 2010// /expblk.c/1.1/Wed Jan 6 16:33:39 2010// /expcab.c/1.1/Wed Jan 6 16:33:39 2010// /expclb.c/1.1/Wed Jan 6 16:33:39 2010// /expcns.c/1.1/Wed Jan 6 16:33:39 2010// /expcon.c/1.1/Wed Jan 6 16:33:39 2010// /expconn.c/1.1/Wed Jan 6 16:33:39 2010// /expcor.c/1.1/Wed Jan 6 16:33:39 2010// /expcset.c/1.1/Wed Jan 6 16:33:39 2010// /expcss.c/1.1/Wed Jan 6 16:33:41 2010// /expean.c/1.1/Wed Jan 6 16:33:42 2010// /expeat.c/1.1/Wed Jan 6 16:33:42 2010// /expelb.c/1.1/Wed Jan 6 16:33:42 2010// /expelc.c/1.1/Wed Jan 6 16:33:42 2010// /expem.c/1.1/Wed Jan 6 16:33:42 2010// /expenm.c/1.1/Wed Jan 6 16:33:42 2010// /expev.c/1.1/Wed Jan 6 16:33:42 2010// /expfrm.c/1.1/Wed Jan 6 16:33:42 2010// /expgv.c/1.1/Wed Jan 6 16:33:42 2010// /expidm.c/1.1/Wed Jan 6 16:33:42 2010// /expinf.c/1.1/Wed Jan 6 16:33:42 2010// /expini.c/1.1/Wed Jan 6 16:33:42 2010// /expinix.c/1.1/Wed Jan 6 16:33:42 2010// /expmap.c/1.1/Wed Jan 6 16:33:42 2010// /expmp.c/1.1/Wed Jan 6 16:33:42 2010// /expnam.c/1.1/Wed Jan 6 16:33:42 2010// /expnams.c/1.1/Wed Jan 6 16:33:42 2010// /expnm.c/1.1/Wed Jan 6 16:33:42 2010// /expnmap.c/1.1/Wed Jan 6 16:33:42 2010// /expnnm.c/1.1/Wed Jan 6 16:33:42 2010// /expnp.c/1.1/Wed Jan 6 16:33:42 2010// /expns.c/1.1/Wed Jan 6 16:33:42 2010// /expnsd.c/1.1/Wed Jan 6 16:33:42 2010// /expnstt.c/1.1/Wed Jan 6 16:33:42 2010// /expnsv.c/1.1/Wed Jan 6 16:33:42 2010// /expnv.c/1.1/Wed Jan 6 16:33:43 2010// /expnvv.c/1.1/Wed Jan 6 16:33:43 2010// /expoatt.c/1.1/Wed Jan 6 16:33:43 2010// /expoea.c/1.1/Wed Jan 6 16:33:43 2010// /expp.c/1.1/Wed Jan 6 16:33:43 2010// /exppa.c/1.1/Wed Jan 6 16:33:43 2010// /exppem.c/1.1/Wed Jan 6 16:33:43 2010// /exppn.c/1.1/Wed Jan 6 16:33:43 2010// /expqa.c/1.1/Wed Jan 6 16:33:43 2010// /expset.c/1.1/Wed Jan 6 16:33:43 2010// /expsetd.c/1.1/Wed Jan 6 16:33:43 2010// /expsetp.c/1.1/Wed Jan 6 16:33:43 2010// /expsp.c/1.1/Wed Jan 6 16:33:43 2010// /expss.c/1.1/Wed Jan 6 16:33:43 2010// /expssd.c/1.1/Wed Jan 6 16:33:43 2010// /expsstt.c/1.1/Wed Jan 6 16:33:43 2010// /expssv.c/1.1/Wed Jan 6 16:33:43 2010// /exptim.c/1.1/Wed Jan 6 16:33:43 2010// /exptt.c/1.1/Wed Jan 6 16:33:43 2010// /expvan.c/1.1/Wed Jan 6 16:33:43 2010// /expvar.c/1.1/Wed Jan 6 16:33:43 2010// /expvarnam.c/1.1/Wed Jan 6 16:33:43 2010// /expvarnams.c/1.1/Wed Jan 6 16:33:43 2010// /expvarparam.c/1.1/Wed Jan 6 16:33:43 2010// /expvartab.c/1.1/Wed Jan 6 16:33:43 2010// /expvnm.c/1.1/Wed Jan 6 16:33:43 2010// /expvp.c/1.1/Wed Jan 6 16:33:43 2010// /expvpa.c/1.1/Wed Jan 6 16:33:44 2010// /expvpax.c/1.1/Wed Jan 6 16:33:47 2010// /expvpc.c/1.1/Wed Jan 6 16:33:49 2010// /expvtt.c/1.1/Wed Jan 6 16:33:51 2010// /expvv.c/1.1/Wed Jan 6 16:33:51 2010// /exupda.c/1.1/Wed Jan 6 16:33:51 2010// D/include//// D/test//// xdmf-2.1.dfsg.1/Utilities/vtkexodus2/CVS/Repository0000644000175000017500000000003211606020250023336 0ustar amckinstryamckinstryXdmf/Utilities/vtkexodus2 xdmf-2.1.dfsg.1/Utilities/vtkexodus2/CVS/Root0000644000175000017500000000006411606020250022107 0ustar amckinstryamckinstry:pserver:anonymous@public.kitware.com:/cvsroot/Xdmf xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgem.c0000755000175000017500000000476311606020250022074 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgem - ex_get_elem_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_id element map id * * exit conditions - * int* elem_map element map * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the element map with specified ID * \deprecated Use ex_get_num_map()(exoid, EX_ELEM_MAP, map_id, elem_map) instead */ int ex_get_elem_map (int exoid, int map_id, int *elem_map) { return ex_get_num_map( exoid, EX_ELEM_MAP, map_id, elem_map ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgcset.c0000644000175000017500000001674211606020250022426 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgcss - ex_get_concat_sets * * entry conditions - * input parameters: * int exoid exodus file id * ex_entity_type set_type type of set * * exit conditions - * struct ex_set_specs* set_specs set specs structure * * revision history - * * $Id: exgcset.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the set ID's, set entry count array, set entry pointers * array, set entry list, set extra list, and set distribution factors * for all sets of the specified type. */ int ex_get_concat_sets (int exoid, ex_entity_type set_type, struct ex_set_specs* set_specs) { int status, dimid; int *set_ids = set_specs->sets_ids; int *num_entries_per_set = set_specs->num_entries_per_set; int *num_dist_per_set = set_specs->num_dist_per_set; int *sets_entry_index = set_specs->sets_entry_index; int *sets_dist_index = set_specs->sets_dist_index; int *sets_entry_list = set_specs->sets_entry_list; int *sets_extra_list = set_specs->sets_extra_list; void *sets_dist_fact = set_specs->sets_dist_fact; char *cdum; int num_sets, i; float fdum; float *flt_dist_fact; double *dbl_dist_fact; char errmsg[MAX_ERR_LENGTH]; ex_inquiry ex_inq_val; exerrval = 0; /* clear error code */ cdum = 0; /* initialize even though it is not used */ /* setup pointers based on set_type NOTE: there is another block that sets more stuff later ... */ if (set_type == EX_NODE_SET) { ex_inq_val = EX_INQ_NODE_SETS; } else if (set_type == EX_EDGE_SET) { ex_inq_val = EX_INQ_EDGE_SETS; } else if (set_type == EX_FACE_SET) { ex_inq_val = EX_INQ_FACE_SETS; } else if (set_type == EX_SIDE_SET) { ex_inq_val = EX_INQ_SIDE_SETS; } else if (set_type == EX_ELEM_SET) { ex_inq_val = EX_INQ_ELEM_SETS; } else { exerrval = EX_FATAL; sprintf(errmsg, "Error: invalid set type (%d)", set_type); ex_err("ex_put_set_param",errmsg,exerrval); return (EX_FATAL); } /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &dimid)) != NC_NOERR) { exerrval = status; if (status == NC_EBADDIM) { sprintf(errmsg, "Warning: no %ss defined for file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_get_concat_sets",errmsg,exerrval); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate %ss defined in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_get_concat_sets",errmsg,exerrval); return (EX_FATAL); } } /* inquire how many sets have been stored */ if (ex_inquire(exoid, ex_inq_val, &num_sets, &fdum, cdum) != NC_NOERR) { sprintf(errmsg, "Error: failed to get number of %ss defined for file id %d", ex_name_of_object(set_type), exoid); /* use error val from inquire */ ex_err("ex_get_concat_sets",errmsg,exerrval); return (EX_FATAL); } if (ex_get_ids (exoid, set_type, set_ids) != NC_NOERR) { sprintf(errmsg, "Error: failed to get %s ids for file id %d", ex_name_of_object(set_type), exoid); /* use error val from inquire */ ex_err("ex_get_concat_sets",errmsg,exerrval); return (EX_FATAL); } sets_entry_index[0] = 0; sets_dist_index[0] = 0; for (i=0; i 0) { /* only get df if they exist */ if (ex_get_set_dist_fact(exoid, set_type, set_ids[i], &(flt_dist_fact[sets_dist_index[i]])) != NC_NOERR) { sprintf(errmsg, "Error: failed to get %s %d dist factors in file id %d", ex_name_of_object(set_type), set_ids[i], exoid); ex_err("ex_get_concat_sets",errmsg,exerrval); return(EX_FATAL); } } else { /* fill distribution factor array with 1's */ } } else if (ex_comp_ws(exoid) == sizeof(double)) { if (ex_get_set(exoid, set_type, set_ids[i], &(sets_entry_list[sets_entry_index[i]]), &(sets_extra_list[sets_entry_index[i]])) != NC_NOERR) return(EX_FATAL); /* error will be reported by subroutine */ /* get distribution factors for this set */ dbl_dist_fact = sets_dist_fact; if (num_dist_per_set[i] > 0) { /* only get df if they exist */ if (ex_get_set_dist_fact(exoid, set_type, set_ids[i], &(dbl_dist_fact[sets_dist_index[i]])) != NC_NOERR) { sprintf(errmsg, "Error: failed to get %s %d dist factors in file id %d", ex_name_of_object(set_type), set_ids[i], exoid); ex_err("ex_get_concat_sets",errmsg,exerrval); return(EX_FATAL); } } else { /* fill distribution factor array with 1's */ } } } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/ex_utils.c0000755000175000017500000011152711606020250022620 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exutils - utility routines * * $Id: ex_utils.c,v 1.1 2010-01-06 16:33:04 kwleiter Exp $ *****************************************************************************/ #if defined(DEBUG_QSORT) #include #endif #include #include #include #include #include "exodusII.h" #include "exodusII_int.h" struct obj_stats* exoII_eb = 0; struct obj_stats* exoII_ed = 0; struct obj_stats* exoII_fa = 0; struct obj_stats* exoII_ns = 0; struct obj_stats* exoII_es = 0; struct obj_stats* exoII_fs = 0; struct obj_stats* exoII_ss = 0; struct obj_stats* exoII_els = 0; struct obj_stats* exoII_em = 0; struct obj_stats* exoII_edm = 0; struct obj_stats* exoII_fam = 0; struct obj_stats* exoII_nm = 0; /***************************************************************************** * * utility routines for string conversions * ex_catstr - concatenate string/number (where number is converted to ASCII) * ex_catstr2 - concatenate string1/number1/string2/number2 " * * NOTE: these routines reuse the same storage over and over to build * concatenated strings, because the strings are just passed to netCDF * routines as names used to look up variables. if the strings returned * by these routines are needed for any other purpose, they should * immediately be copied into other storage. *****************************************************************************/ static char ret_string[10*(MAX_VAR_NAME_LENGTH+1)]; static char* cur_string = &ret_string[0]; /** ex_catstr - concatenate string/number (where number is converted to ASCII) */ char *ex_catstr (const char *string, int num) { char* tmp_string = cur_string; cur_string += sprintf (cur_string, "%s%d", string, num) + 1; if ( cur_string - ret_string > 9*(MAX_VAR_NAME_LENGTH+1) ) cur_string = ret_string; return (tmp_string); } /** ex_catstr2 - concatenate string1num1string2num2 */ char *ex_catstr2 (const char *string1, int num1, const char *string2, int num2) { char* tmp_string = cur_string; cur_string += sprintf (cur_string, "%s%d%s%d", string1, num1, string2, num2) + 1; if ( cur_string - ret_string > 9*(MAX_VAR_NAME_LENGTH+1) ) cur_string = ret_string; return (tmp_string); } const char* ex_name_of_object(ex_entity_type obj_type) { switch (obj_type) { case EX_NODAL: return "nodal"; case EX_EDGE_BLOCK: return "edge block"; case EX_FACE_BLOCK: return "face block"; case EX_ELEM_BLOCK: return "element block"; case EX_NODE_SET: return "node set"; case EX_EDGE_SET: return "edge set"; case EX_FACE_SET: return "face set"; case EX_SIDE_SET: return "side set"; case EX_ELEM_SET: return "element set"; case EX_ELEM_MAP: return "element map"; case EX_NODE_MAP: return "node map"; case EX_EDGE_MAP: return "edge map"; case EX_FACE_MAP: return "face map"; case EX_GLOBAL: return "global"; default: return "invalid type"; } } ex_entity_type ex_var_type_to_ex_entity_type(char var_type) { char var_lower = tolower(var_type); if (var_lower == 'n') return EX_NODAL; else if (var_lower == 'l') return EX_EDGE_BLOCK; else if (var_lower == 'f') return EX_FACE_BLOCK; else if (var_lower == 'e') return EX_ELEM_BLOCK; else if (var_lower == 'm') return EX_NODE_SET; else if (var_lower == 'd') return EX_EDGE_SET; else if (var_lower == 'a') return EX_FACE_SET; else if (var_lower == 's') return EX_SIDE_SET; else if (var_lower == 't') return EX_ELEM_SET; else if (var_lower == 'g') return EX_GLOBAL; else return EX_INVALID; } const char* ex_dim_num_objects(ex_entity_type obj_type) { exerrval = 0; /* clear error code */ switch (obj_type) { case EX_NODAL: return DIM_NUM_NODES; case EX_ELEM_BLOCK: return DIM_NUM_EL_BLK; case EX_EDGE_BLOCK: return DIM_NUM_ED_BLK; case EX_FACE_BLOCK: return DIM_NUM_FA_BLK; case EX_NODE_SET: return DIM_NUM_NS; case EX_EDGE_SET: return DIM_NUM_ES; case EX_FACE_SET: return DIM_NUM_FS; case EX_ELEM_SET: return DIM_NUM_ELS; case EX_SIDE_SET: return DIM_NUM_SS; case EX_ELEM_MAP: return DIM_NUM_EM; case EX_FACE_MAP: return DIM_NUM_FAM; case EX_EDGE_MAP: return DIM_NUM_EDM; case EX_NODE_MAP: return DIM_NUM_NM; default: { char errmsg[MAX_ERR_LENGTH]; exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported in call to ex_dim_num_objects", obj_type); ex_err("ex_dim_num_objects",errmsg,exerrval); return (NULL); } } } const char* ex_dim_num_entries_in_object( ex_entity_type obj_type, int idx ) { switch (obj_type) { case EX_NODAL: return DIM_NUM_NODES; case EX_EDGE_BLOCK: return DIM_NUM_ED_IN_EBLK(idx); case EX_FACE_BLOCK: return DIM_NUM_FA_IN_FBLK(idx); case EX_ELEM_BLOCK: return DIM_NUM_EL_IN_BLK(idx); case EX_NODE_SET: return DIM_NUM_NOD_NS(idx); case EX_EDGE_SET: return DIM_NUM_EDGE_ES(idx); case EX_FACE_SET: return DIM_NUM_FACE_FS(idx); case EX_SIDE_SET: return DIM_NUM_SIDE_SS(idx); case EX_ELEM_SET: return DIM_NUM_ELE_ELS(idx); default: return 0; } } char* ex_name_var_of_object(ex_entity_type obj_type, int i, int j) { switch (obj_type) { case EX_EDGE_BLOCK: return VAR_EDGE_VAR(i,j); case EX_FACE_BLOCK: return VAR_FACE_VAR(i,j); case EX_ELEM_BLOCK: return VAR_ELEM_VAR(i,j); case EX_NODE_SET: return VAR_NS_VAR(i,j); case EX_EDGE_SET: return VAR_ES_VAR(i,j); case EX_FACE_SET: return VAR_FS_VAR(i,j); case EX_SIDE_SET: return VAR_SS_VAR(i,j); case EX_ELEM_SET: return VAR_ELS_VAR(i,j); default: return 0; } } char* ex_name_of_map(ex_entity_type map_type, int map_index) { switch (map_type) { case EX_NODE_MAP: return VAR_NODE_MAP(map_index); case EX_EDGE_MAP: return VAR_EDGE_MAP(map_index); case EX_FACE_MAP: return VAR_FACE_MAP(map_index); case EX_ELEM_MAP: return VAR_ELEM_MAP(map_index); default: return 0; } } /***************************************************************************** * * ex_id_lkup - look up id * * entry conditions - * input parameters: * int exoid exodus file id * ex_entity_type id_type id type name: * elem_ss * node_ns * side_ss * int num id value * * exit conditions - * int return index into table (1-based) * * revision history - * * *****************************************************************************/ int ex_id_lkup( int exoid, ex_entity_type id_type, int num) { char id_table[MAX_VAR_NAME_LENGTH+1]; char id_dim[MAX_VAR_NAME_LENGTH+1]; char stat_table[MAX_VAR_NAME_LENGTH+1]; int varid, dimid; size_t dim_len, i; int *id_vals=NULL, *stat_vals=NULL; static int filled=FALSE; struct obj_stats *tmp_stats; int status; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ switch(id_type) { case EX_NODAL: return 0; case EX_GLOBAL: return 0; case EX_ELEM_BLOCK: strcpy(id_table, VAR_ID_EL_BLK); /* id array name */ strcpy(id_dim, DIM_NUM_EL_BLK); /* id array dimension name*/ strcpy(stat_table, VAR_STAT_EL_BLK); /* id status array name */ tmp_stats = ex_get_stat_ptr (exoid, &exoII_eb); break; case EX_NODE_SET: strcpy(id_table, VAR_NS_IDS); strcpy(id_dim, DIM_NUM_NS); strcpy(stat_table, VAR_NS_STAT); tmp_stats = ex_get_stat_ptr (exoid, &exoII_ns); break; case EX_SIDE_SET: strcpy(id_table, VAR_SS_IDS); strcpy(id_dim, DIM_NUM_SS); strcpy(stat_table, VAR_SS_STAT); tmp_stats = ex_get_stat_ptr (exoid, &exoII_ss); break; case EX_ELEM_MAP: strcpy(id_table, VAR_EM_PROP(1)); strcpy(id_dim, DIM_NUM_EM); strcpy(stat_table, ""); tmp_stats = ex_get_stat_ptr (exoid, &exoII_em); break; case EX_NODE_MAP: strcpy(id_table, VAR_NM_PROP(1)); strcpy(id_dim, DIM_NUM_NM); strcpy(stat_table, ""); tmp_stats = ex_get_stat_ptr (exoid, &exoII_nm); break; case EX_EDGE_BLOCK: strcpy(id_table, VAR_ID_ED_BLK); strcpy(id_dim, DIM_NUM_ED_BLK); strcpy(stat_table, VAR_STAT_ED_BLK); tmp_stats = ex_get_stat_ptr (exoid, &exoII_ed); break; case EX_FACE_BLOCK: strcpy(id_table, VAR_ID_FA_BLK); strcpy(id_dim, DIM_NUM_FA_BLK); strcpy(stat_table, VAR_STAT_FA_BLK); tmp_stats = ex_get_stat_ptr (exoid, &exoII_fa); break; case EX_EDGE_SET: strcpy(id_table, VAR_ES_IDS); strcpy(id_dim, DIM_NUM_ES); strcpy(stat_table, VAR_ES_STAT); tmp_stats = ex_get_stat_ptr (exoid, &exoII_es); break; case EX_FACE_SET: strcpy(id_table, VAR_FS_IDS); strcpy(id_dim, DIM_NUM_FS); strcpy(stat_table, VAR_FS_STAT); tmp_stats = ex_get_stat_ptr (exoid, &exoII_fs); break; case EX_ELEM_SET: strcpy(id_table, VAR_ELS_IDS); strcpy(id_dim, DIM_NUM_ELS); strcpy(stat_table, VAR_ELS_STAT); tmp_stats = ex_get_stat_ptr (exoid, &exoII_els); break; case EX_EDGE_MAP: strcpy(id_table, VAR_EDM_PROP(1)); strcpy(id_dim, DIM_NUM_EDM); strcpy(stat_table, ""); tmp_stats = ex_get_stat_ptr (exoid, &exoII_edm); break; case EX_FACE_MAP: strcpy(id_table, VAR_FAM_PROP(1)); strcpy(id_dim, DIM_NUM_FAM); strcpy(stat_table, ""); tmp_stats = ex_get_stat_ptr (exoid, &exoII_fam); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: unsupported id array type %d for file id %d", id_type, exoid); ex_err("ex_id_lkup",errmsg,exerrval); return (EX_FATAL); } if ( (tmp_stats->id_vals == NULL) || (!(tmp_stats->valid_ids)) ) { /* first time thru or id arrays haven't been completely filled yet */ /* get size of id array */ /* First get dimension id of id array */ if ((status = nc_inq_dimid(exoid,id_dim,&dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate id array dimension in file id %d", exoid); ex_err("ex_id_lkup",errmsg,exerrval); return (EX_FATAL); } /* Next get value of dimension */ if ((status = nc_inq_dimlen(exoid,dimid,&dim_len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s array length in file id %d", id_table,exoid); ex_err("ex_id_lkup",errmsg,exerrval); return (EX_FATAL); } /* get variable id of id array */ if ((status = nc_inq_varid (exoid, id_table, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s array in file id %d", id_table, exoid); ex_err("ex_id_lkup",errmsg,exerrval); return (EX_FATAL); } /* allocate space for id array */ if (!(id_vals = malloc((int)dim_len*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate memory for %s array for file id %d", id_table,exoid); ex_err("ex_id_lkup",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_get_var_int (exoid, varid, id_vals)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s array from file id %d", id_table,exoid); ex_err("ex_id_lkup",errmsg,exerrval); free(id_vals); return (EX_FATAL); } /* check if values in stored arrays are filled with non-zeroes */ filled = TRUE; for (i=0;ivalid_ids = TRUE; tmp_stats->num = dim_len; tmp_stats->id_vals = id_vals; } } else { id_vals = tmp_stats->id_vals; dim_len = tmp_stats->num; } /* Do a linear search through the id array to find the array value corresponding to the passed index number */ for (i=0;i= dim_len) /* failed to find id number */ { if ( !(tmp_stats->valid_ids) ) { free (id_vals); } exerrval = EX_LOOKUPFAIL; return(EX_LOOKUPFAIL); /*if we got here, the id array value doesn't exist */ } /* Now check status array to see if object is null */ /* get variable id of status array */ if (nc_inq_varid (exoid, stat_table, &varid) == NC_NOERR) { /* if status array exists, use it, otherwise assume object exists to be backward compatible */ if ( (tmp_stats->stat_vals == NULL) || (!(tmp_stats->valid_stat)) ) { /* first time thru or status arrays haven't been filled yet */ /* allocate space for new status array */ if (!(stat_vals = malloc((int)dim_len*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate memory for %s array for file id %d", id_table,exoid); ex_err("ex_id_lkup",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_get_var_int (exoid, varid, stat_vals)) != NC_NOERR) { exerrval = status; free(stat_vals); sprintf(errmsg, "Error: failed to get %s array from file id %d", stat_table,exoid); ex_err("ex_id_lkup",errmsg,exerrval); return (EX_FATAL); } if (tmp_stats->valid_ids) { /* status array is valid only if ids are valid */ tmp_stats->valid_stat = TRUE; tmp_stats->stat_vals = stat_vals; } } else { stat_vals = tmp_stats->stat_vals; } if (stat_vals[i] == 0) /* is this object null? */ { exerrval = EX_NULLENTITY; if ( !(tmp_stats->valid_stat) ) { free (stat_vals); } if ( !(tmp_stats->valid_ids) ) { if (id_vals) free (id_vals); } return(-(((int)i)+1)); /* return index into id array (1-based) */ } } if ( !(tmp_stats->valid_ids) ) { if (id_vals) free (id_vals); if (stat_vals) free (stat_vals); } return(i+1); /* return index into id array (1-based) */ } /****************************************************************************** * * ex_get_stat_ptr - returns a pointer to a structure of object ids * * revision history - * * *****************************************************************************/ /*! this routine returns a pointer to a structure containing the ids of * element blocks, node sets, or side sets according to exoid; if there * is not a structure that matches the exoid, one is created */ struct obj_stats *ex_get_stat_ptr (int exoid, struct obj_stats **obj_ptr) { struct obj_stats *tmp_ptr; tmp_ptr = *obj_ptr; while (tmp_ptr) { if ( (tmp_ptr)->exoid == exoid) { break; } tmp_ptr = (tmp_ptr)->next; } if (!tmp_ptr) { /* exoid not found */ tmp_ptr = (struct obj_stats *) calloc (1, sizeof(struct obj_stats)); tmp_ptr->exoid = exoid; tmp_ptr->next = *obj_ptr; tmp_ptr->id_vals = 0; tmp_ptr->stat_vals = 0; tmp_ptr->num = 0; tmp_ptr->valid_ids = 0; tmp_ptr->valid_stat = 0; *obj_ptr = tmp_ptr; } return (tmp_ptr); } /****************************************************************************** * * ex_rm_stat_ptr - removes a pointer to a structure of object ids * * revision history - * * *****************************************************************************/ /*! this routine removes a pointer to a structure containing the ids of * element blocks, node sets, or side sets according to exoid; this * is necessary to clean up because netCDF reuses file ids; should be * called from ex_close */ void ex_rm_stat_ptr (int exoid, struct obj_stats **obj_ptr) { struct obj_stats *last_head_list_ptr, *tmp_ptr; tmp_ptr = *obj_ptr; last_head_list_ptr = *obj_ptr; /* save last head pointer */ while (tmp_ptr ) /* Walk linked list of file ids/vals */ { if (exoid == tmp_ptr->exoid ) /* linear search for exodus file id */ { if (tmp_ptr == *obj_ptr) /* Are we at the head of the list? */ *obj_ptr = (*obj_ptr)->next; /* yes, reset ptr to head of list */ else /* no, remove this record from chain*/ last_head_list_ptr->next=tmp_ptr->next; if (tmp_ptr->id_vals != NULL) free(tmp_ptr->id_vals); /* free up memory */ if (tmp_ptr->stat_vals != NULL) free(tmp_ptr->stat_vals); free(tmp_ptr); break; /* Quit if found */ } last_head_list_ptr = tmp_ptr; /* save last head pointer */ tmp_ptr = tmp_ptr->next; /* Loop back if not */ } } /* structures to hold number of blocks of that type for each file id */ static struct list_item* ed_ctr_list = 0; /* edge blocks */ static struct list_item* fa_ctr_list = 0; /* face blocks */ static struct list_item* eb_ctr_list = 0; /* element blocks */ /* structures to hold number of sets of that type for each file id */ static struct list_item* ns_ctr_list = 0; /* node sets */ static struct list_item* es_ctr_list = 0; /* edge sets */ static struct list_item* fs_ctr_list = 0; /* face sets */ static struct list_item* ss_ctr_list = 0; /* side sets */ static struct list_item* els_ctr_list = 0; /* element sets */ /* structures to hold number of maps of that type for each file id */ static struct list_item* nm_ctr_list = 0; /* node maps */ static struct list_item* edm_ctr_list = 0; /* edge maps */ static struct list_item* fam_ctr_list = 0; /* face maps */ static struct list_item* em_ctr_list = 0; /* element maps */ struct list_item** ex_get_counter_list(ex_entity_type obj_type) { switch(obj_type) { case EX_ELEM_BLOCK: return &eb_ctr_list; case EX_NODE_SET: return &ns_ctr_list; case EX_SIDE_SET: return &ss_ctr_list; case EX_ELEM_MAP: return &em_ctr_list; case EX_NODE_MAP: return &nm_ctr_list; case EX_EDGE_BLOCK: return &ed_ctr_list; case EX_FACE_BLOCK: return &fa_ctr_list; case EX_EDGE_SET: return &es_ctr_list; case EX_FACE_SET: return &fs_ctr_list; case EX_ELEM_SET: return &els_ctr_list; case EX_EDGE_MAP: return &edm_ctr_list; case EX_FACE_MAP: return &fam_ctr_list; default: return (NULL); } } /****************************************************************************** * * ex_inc_file_item - increment file item * *****************************************************************************/ /*! this routine sets up a structure to track and increment a counter for * each open exodus file. it is designed to be used by the routines * ex_put_elem_block() and ex_put_set_param(), * to keep track of the number of element blocks, and each type of set, * respectively, for each open exodus II file. * * The list structure is used as follows: * * ptr -----------> list item structure * ------------------- * exodus file id * item value (int) * ptr to next (NULL if last) * * * NOTE: since netCDF reuses its file ids, and a user may open and close any * number of files in one application, items must be taken out of the * linked lists in each of the above routines. these should be called * after ncclose(). */ int ex_inc_file_item( int exoid, /* file id */ struct list_item **list_ptr)/* ptr to ptr to list_item */ { struct list_item* tlist_ptr; /* printf("[f] list: %ld, *list: %ld \n", list_ptr, *list_ptr); */ tlist_ptr = *list_ptr; /* use temp list ptr to walk linked list */ while (tlist_ptr ) /* Walk linked list of file ids/vals */ { if (exoid == tlist_ptr->exo_id ) /* linear search for exodus file id */ break; /* Quit if found */ tlist_ptr = tlist_ptr->next; /* Loop back if not */ } if (!tlist_ptr ) /* ptr NULL? */ { /* yes, new file id */ /* allocate space for new structure record */ tlist_ptr = (struct list_item*) calloc(1,sizeof(struct list_item)); tlist_ptr->exo_id = exoid; /* insert file id */ tlist_ptr->next = *list_ptr; /* insert into head of list */ *list_ptr = tlist_ptr; /* fix up new head of list */ } /* printf("[f] tlist: %ld *tlist: %ld **tlist: %ld\n", tlist_ptr,*tlist_ptr,(*tlist_ptr)->value, (*tlist_ptr)->next); */ return(tlist_ptr->value++); } /***************************************************************************** * * ex_get_file_item - increment file item * *****************************************************************************/ /*! this routine accesses a structure to track and increment a counter for * each open exodus file. it is designed to be used by the routines * ex_put_elem_block(), and ex_put_set_param(), * to get the number of element blocks, or a type of set, * respectively, for an open exodus II file. * * The list structure is used as follows: * * ptr -----------> list item structure * ------------------- * exodus file id * item value (int) * ptr to next (NULL if last) * * * NOTE: since netCDF reuses its file ids, and a user may open and close any * number of files in one application, items must be taken out of the * linked lists in each of the above routines. these should be called * after ncclose(). */ int ex_get_file_item( int exoid, /* file id */ struct list_item **list_ptr)/* ptr to ptr to list_item */ { struct list_item* tlist_ptr; /* printf("[f] list: %ld, *list: %ld \n", list_ptr, *list_ptr); */ tlist_ptr = *list_ptr; /* use temp list ptr to walk linked list */ while (tlist_ptr ) /* Walk linked list of file ids/vals */ { if (exoid == tlist_ptr->exo_id ) /* linear search for exodus file id */ break; /* Quit if found */ tlist_ptr = tlist_ptr->next; /* Loop back if not */ } if (!tlist_ptr ) /* ptr NULL? */ { /* yes, Error: file id not found*/ return(-1); } /* printf("[f] list: %ld *list: %ld **list: %ld\n", list_ptr,*list_ptr,(*list_ptr)->value, (*list_ptr)->next); */ return(tlist_ptr->value); } /***************************************************************************** * * ex_rm_file_item - remove file item * *****************************************************************************/ /*! this routine removes a structure to track and increment a counter for * each open exodus file. * * The list structure is used as follows: * * ptr -----------> list item structure * ------------------- * exodus file id * item value (int) * ptr to next (NULL if last) * * * NOTE: since netCDF reuses its file ids, and a user may open and close any * number of files in one application, items must be taken out of the * linked lists in each of the above routines. these should be called * after ncclose(). */ void ex_rm_file_item( int exoid, /* file id */ struct list_item **list_ptr)/* ptr to ptr to list_item */ { struct list_item *last_head_list_ptr, *tlist_ptr; /* printf("[f] list: %ld, *list: %ld \n", list_ptr, *list_ptr); */ tlist_ptr = *list_ptr; last_head_list_ptr = *list_ptr; /* save last head pointer */ /* printf("[f] last head list: %ld\n",last_head_list_ptr); */ while (tlist_ptr ) /* Walk linked list of file ids/vals */ { if (exoid == tlist_ptr->exo_id ) /* linear search for exodus file id */ { if (tlist_ptr == *list_ptr) /* Are we at the head of the list? */ *list_ptr = (*list_ptr)->next; /* yes, reset ptr to head of list */ else /* no, remove this record from chain*/ last_head_list_ptr->next=tlist_ptr->next; free(tlist_ptr); /* free up memory */ break; /* Quit if found */ } last_head_list_ptr = tlist_ptr; /* save last head pointer */ tlist_ptr = tlist_ptr->next; /* Loop back if not */ } /* printf("[f] list: %ld *list: %ld **list: %ld\n", list_ptr,*list_ptr,(*list_ptr)->value, (*list_ptr)->next); */ } /***************************************************************************** * * ex_get_num_props - get number of properties * * entry conditions - * * exit conditions - * * revision history - * * *****************************************************************************/ int ex_get_num_props (int exoid, ex_entity_type obj_type) { int cntr, varid; char var_name[MAX_VAR_NAME_LENGTH+1]; char errmsg[MAX_ERR_LENGTH]; cntr = 0; /* loop until there is not a property variable defined; the name of */ /* the variables begin with an increment of 1 ("xx_prop1") so use cntr+1 */ while (TRUE) { switch (obj_type) { case EX_ELEM_BLOCK: strcpy (var_name, VAR_EB_PROP(cntr+1)); break; case EX_EDGE_BLOCK: strcpy (var_name, VAR_ED_PROP(cntr+1)); break; case EX_FACE_BLOCK: strcpy (var_name, VAR_FA_PROP(cntr+1)); break; case EX_NODE_SET: strcpy (var_name, VAR_NS_PROP(cntr+1)); break; case EX_EDGE_SET: strcpy (var_name, VAR_ES_PROP(cntr+1)); break; case EX_FACE_SET: strcpy (var_name, VAR_FS_PROP(cntr+1)); break; case EX_SIDE_SET: strcpy (var_name, VAR_SS_PROP(cntr+1)); break; case EX_ELEM_SET: strcpy (var_name, VAR_ELS_PROP(cntr+1)); break; case EX_ELEM_MAP: strcpy (var_name, VAR_EM_PROP(cntr+1)); break; case EX_FACE_MAP: strcpy (var_name, VAR_FAM_PROP(cntr+1)); break; case EX_EDGE_MAP: strcpy (var_name, VAR_EDM_PROP(cntr+1)); break; case EX_NODE_MAP: strcpy (var_name, VAR_NM_PROP(cntr+1)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_get_prop_names",errmsg,exerrval); return(EX_FATAL); } if (nc_inq_varid (exoid, var_name, &varid) != NC_NOERR) { /* no variable with this name; return cntr which is now the number of */ /* properties for this type of entity */ return (cntr); } cntr++; } } int ex_get_cpu_ws(void) { return(sizeof(float)); } /* swap - interchange v[i] and v[j] */ static void ex_swap (int v[], int i, int j) { int temp; temp = v[i]; v[i] = v[j]; v[j] = temp; } /*! * The following 'indexed qsort' routine is modified from Sedgewicks * algorithm It selects the pivot based on the median of the left, * right, and center values to try to avoid degenerate cases ocurring * when a single value is chosen. It performs a quicksort on * intervals down to the EX_QSORT_CUTOFF size and then performs a final * insertion sort on the almost sorted final array. Based on data in * Sedgewick, the EX_QSORT_CUTOFF value should be between 5 and 20. * * See Sedgewick for further details * Define DEBUG_QSORT at the top of this file and recompile to compile * in code that verifies that the array is sorted. */ #define EX_QSORT_CUTOFF 12 static int ex_int_median3(int v[], int iv[], int left, int right) { int center; center = (left + right) / 2; if (v[iv[left]] > v[iv[center]]) ex_swap(iv, left, center); if (v[iv[left]] > v[iv[right]]) ex_swap(iv, left, right); if (v[iv[center]] > v[iv[right]]) ex_swap(iv, center, right); ex_swap(iv, center, right-1); return iv[right-1]; } static void ex_int_iqsort(int v[], int iv[], int left, int right) { int pivot; int i, j; if (left + EX_QSORT_CUTOFF <= right) { pivot = ex_int_median3(v, iv, left, right); i = left; j = right - 1; for ( ; ; ) { while (v[iv[++i]] < v[pivot]); while (v[iv[--j]] > v[pivot]); if (i < j) { ex_swap(iv, i, j); } else { break; } } ex_swap(iv, i, right-1); ex_int_iqsort(v, iv, left, i-1); ex_int_iqsort(v, iv, i+1, right); } } static void ex_int_iisort(int v[], int iv[], int N) { int i,j; int ndx = 0; int small; int tmp; small = v[iv[0]]; for (i = 1; i < N; i++) { if (v[iv[i]] < small) { small = v[iv[i]]; ndx = i; } } /* Put smallest value in slot 0 */ ex_swap(iv, 0, ndx); for (i=1; i 0) { /* Allocate storage for element block parameters... */ int *ids = malloc(num_eblk * sizeof(int)); size_t i; size += 2*num_eblk; /* status + ids */ ex_get_ids(exoid, EX_ELEM_BLOCK, ids); for (i=0; i < num_eblk; i++) { int num_elem_this_blk = 0; int num_nodes_per_elem = 0; int num_attr = 0; char elem_type[MAX_STR_LENGTH+1]; ex_get_elem_block(exoid, ids[i], elem_type, &num_elem_this_blk, &num_nodes_per_elem, &num_attr); size += num_elem_this_blk * num_nodes_per_elem; size += num_elem_this_blk * num_attr * iows; } free(ids); } /* Nodesets */ ex_get_dimension(exoid, DIM_NUM_NS, "nodesets", &num_nset, &temp, routine); if (num_nset > 0) { /* Allocate storage for nodeset parameters... */ int *ids = malloc(num_nset * sizeof(int)); size_t i; size += 2*num_nset; /* Status + ids */ ex_get_ids(exoid, EX_NODE_SET, ids); for (i=0; i < num_nset; i++) { int num_nodes_in_set = 0; int num_df_in_set = 0; ex_get_node_set_param(exoid, ids[i], &num_nodes_in_set, &num_df_in_set); size += num_nodes_in_set; size += num_df_in_set * iows; } free(ids); } /* Sidesets */ ex_get_dimension(exoid, DIM_NUM_SS, "sidesets", &num_sset, &temp, routine); if (num_sset > 0) { /* Allocate storage for sideset parameters... */ int *ids = malloc(num_sset * sizeof(int)); size_t i; size += 2*num_sset; /* Status + ids */ ex_get_ids(exoid, EX_SIDE_SET, ids); for (i=0; i < num_sset; i++) { int num_sides_in_set = 0; int num_df_in_set = 0; ex_get_side_set_param(exoid, ids[i], &num_sides_in_set, &num_df_in_set); size += num_sides_in_set * 2; size += num_df_in_set * iows; } free(ids); } if (ex_large_model(exoid) == 0 && size > (1<<29)) { fprintf(stderr, "ERROR: Size to store header information exceeds 2GB in file id %d\n File is probably corrupt, rerun with environment variable EXODUS_LARGE_MODEL set.\n", exoid); } return size; } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnmap.c0000644000175000017500000001152111606020250022411 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnm - ex_get_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_type type of map (node, edge, face, element) * int map_id map id * * exit conditions - * int* map map * * revision history - * 20060930 - David Thompson - Adapted from ex_get_node_map * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the map with specified ID */ int ex_get_num_map ( int exoid, ex_entity_type map_type, int map_id, int* map ) { int dimid, var_id, id_ndx, status; char errmsg[MAX_ERR_LENGTH]; const char* dim_map_size; const char* dim_num_maps; switch (map_type) { case EX_NODE_MAP: dim_map_size = DIM_NUM_NODES; dim_num_maps = DIM_NUM_NM; break; case EX_EDGE_MAP: dim_map_size = DIM_NUM_EDGE; dim_num_maps = DIM_NUM_EDM; break; case EX_FACE_MAP: dim_map_size = DIM_NUM_FACE; dim_num_maps = DIM_NUM_FAM; break; case EX_ELEM_MAP: dim_map_size = DIM_NUM_ELEM; dim_num_maps = DIM_NUM_EM; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Bad map type (%d) specified", map_type ); ex_err( "ex_get_num_map", errmsg, exerrval ); return (EX_FATAL); } exerrval = 0; /* clear error code */ /* See if any entries are stored in this file */ if (nc_inq_dimid (exoid, dim_map_size, &dimid) != NC_NOERR) { return (EX_NOERR); } /* first check if any maps have been defined */ if ((status = nc_inq_dimid(exoid, dim_num_maps, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no %ss defined in file id %d", ex_name_of_object(map_type),exoid); ex_err("ex_get_map",errmsg,exerrval); return (EX_WARN); } /* Lookup index of map id property array */ id_ndx = ex_id_lkup(exoid,map_type,map_id); if (exerrval != 0) { sprintf(errmsg, "Error: failed to locate %s id %d in id variable in file id %d", ex_name_of_object(map_type),map_id,exoid); ex_err("ex_get_map",errmsg,exerrval); return (EX_FATAL); } /* inquire id's of previously defined dimensions and variables */ if ((status = nc_inq_varid(exoid, ex_name_of_map(map_type,id_ndx), &var_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s %d in file id %d", ex_name_of_object(map_type),map_id,exoid); ex_err("ex_get_map",errmsg,exerrval); return (EX_FATAL); } /* read in the map */ status = nc_get_var_int(exoid, var_id, map); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s in file id %d", ex_name_of_object(map_type),exoid); ex_err("ex_get_map",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvid.c0000644000175000017500000001263711606020250022251 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvid - ex_get_varid * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int* varid variable id array * * revision history - * * $Id: exgvid.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the EXODUS II variable varids from the database */ int ex_get_varid (int exoid, ex_entity_type obj_type, int *varid_arr) { int status1, status2; size_t i, j; int varid; size_t num_entity = 0; size_t num_var = 0; char errmsg[MAX_ERR_LENGTH]; const char* routine = "ex_get_varid"; /* * The ent_type and the var_name are used to build the netcdf * variables name. Normally this is done via a macro defined in * exodusII_int.h */ const char* ent_type = NULL; const char* var_name = NULL; exerrval = 0; /* clear error code */ if (obj_type == EX_NODAL){ /* Handle nodal variables in a node-specific manner */ return ex_get_nodal_varid(exoid, varid_arr); } else if (obj_type == EX_ELEM_BLOCK) { status1 = ex_get_dimension(exoid, DIM_NUM_ELE_VAR, "element variables", &num_var, &varid, routine); var_name = "vals_elem_var"; ent_type = "eb"; } else if (obj_type == EX_NODE_SET) { status1 = ex_get_dimension(exoid, DIM_NUM_NSET_VAR, "nodeset variables", &num_var, &varid, routine); var_name = "vals_nset_var"; ent_type = "ns"; } else if (obj_type == EX_SIDE_SET) { status1 = ex_get_dimension(exoid, DIM_NUM_SSET_VAR, "sideset variables", &num_var, &varid, routine); var_name = "vals_sset_var"; ent_type = "ss"; } else if (obj_type == EX_EDGE_BLOCK) { status1 = ex_get_dimension(exoid, DIM_NUM_EDG_VAR, "edge variables", &num_var, &varid, routine); var_name = "vals_edge_var"; ent_type = "eb"; } else if (obj_type == EX_EDGE_SET) { status1 = ex_get_dimension(exoid, DIM_NUM_ESET_VAR, "edgeset variables", &num_var, &varid, routine); var_name = "vals_eset_var"; ent_type = "es"; } else if (obj_type == EX_FACE_BLOCK) { status1 = ex_get_dimension(exoid, DIM_NUM_FAC_VAR, "face variables", &num_var, &varid, routine); var_name = "vals_face_var"; ent_type = "fb"; } else if (obj_type == EX_FACE_SET) { status1 = ex_get_dimension(exoid, DIM_NUM_FSET_VAR, "faceset variables", &num_var, &varid, routine); var_name = "vals_fset_var"; ent_type = "fs"; } else if (obj_type == EX_ELEM_SET) { status1 = ex_get_dimension(exoid, DIM_NUM_ELSET_VAR, "elementset variables", &num_var, &varid, routine); var_name = "vals_elset_var"; ent_type = "es"; } else { /* invalid variable type */ exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid object type %d specified in file id %d", obj_type, exoid); ex_err("ex_get_varid",errmsg,exerrval); return (EX_WARN); } status2 = ex_get_dimension(exoid, ex_dim_num_objects(obj_type), ex_name_of_object(obj_type), &num_entity, &varid, routine); if (status2 != NC_NOERR || status1 != NC_NOERR) return(EX_FATAL); if (num_entity == 0 || num_var == 0) return(EX_WARN); for (j=0; j #include "exodusII.h" #include "exodusII_int.h" /*! * reads the EXODUS II nodeset variable truth table from the database * \deprecated Use ex_get_truth_table()(exoid, EX_NODE_SET, num_nodesets, num_nset_var, nset_var_tab) */ int ex_get_nset_var_tab (int exoid, int num_nodesets, int num_nset_var, int *nset_var_tab) { return ex_get_truth_table(exoid, EX_NODE_SET, num_nodesets, num_nset_var, nset_var_tab); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgnvv.c0000755000175000017500000000745511606020250022305 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnv - ex_get_nodal_varid_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step whole time step number * int nodal_var_index index of desired nodal variable * int num_nodes number of nodal points * int varid id of variable on exodus database * * exit conditions - * float* nodal_var_vals array of nodal variable values * * revision history - * * $Id: exgnvv.c,v 1.1 2010-01-06 16:33:29 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the values of a single nodal variable for a single time step from * the database; assume the first time step and nodal variable index is 1 */ int ex_get_nodal_varid_var(int exoid, int time_step, int nodal_var_index, int num_nodes, int varid, void *nodal_var_vals) { int status; size_t start[3], count[3]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined variable */ if (ex_large_model(exoid) == 0) { start[0] = --time_step; start[1] = --nodal_var_index; start[2] = 0; count[0] = 1; count[1] = 1; count[2] = num_nodes; } else { start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_nodes; } if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, nodal_var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, nodal_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get nodal variables in file id %d", exoid); ex_err("ex_get_nodal_varid_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgcor.c0000755000175000017500000001667711606020250022265 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgcor - ex_get_coord * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * float* x_coord X coord array * float* y_coord y coord array * float* z_coord z coord array * * revision history - * * $Id: exgcor.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the coordinates of the nodes. * Memory must be allocated for the coordinate arrays (x_coor, y_coor, * and z_coor) before this call is made. The length of each of these * arrays is the number of nodes in the mesh. Because the coordinates * are floating point values, the application code must declare the * arrays passed to be the appropriate type "float" or "double" * to match the compute word size passed in ex_create() or ex_open() * \param exoid exodus file id * \param[out] x_coor Returned X coordinates of the nodes. These are * returned only if x_coor is non-NULL. * \param[out] y_coor Returned Y coordinates of the nodes. These are * returned only if y_coor is non-NULL. * \param[out] z_coor Returned Z coordinates of the nodes. These are * returned only if z_coor is non-NULL. */ int ex_get_coord (int exoid, void *x_coor, void *y_coor, void *z_coor) { int status; int coordid; int coordidx, coordidy, coordidz; int numnoddim, ndimdim; size_t i, num_nod, num_dim, start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* inquire id's of previously defined dimensions */ if (nc_inq_dimid (exoid, DIM_NUM_NODES, &numnoddim) != NC_NOERR) { /* If not found, then this file is storing 0 nodes. Return immediately */ return (EX_NOERR); } if ((status = nc_inq_dimlen(exoid, numnoddim, &num_nod)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of nodes in file id %d", exoid); ex_err("ex_get_coord",errmsg,exerrval); return (EX_FATAL); } if (ex_get_dimension(exoid, DIM_NUM_DIM, "dimensions", &num_dim, &ndimdim, "ex_get_coord") != NC_NOERR) { return(EX_FATAL); } /* read in the coordinates */ if (ex_large_model(exoid) == 0) { if ((status = nc_inq_varid (exoid, VAR_COORD, &coordid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate nodal coordinates in file id %d", exoid); ex_err("ex_get_coord",errmsg,exerrval); return (EX_FATAL); } for (i=0; i 1) { if ((status = nc_inq_varid (exoid, VAR_COORD_Y, &coordidy)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate y nodal coordinates in file id %d", exoid); ex_err("ex_get_coord",errmsg,exerrval); return (EX_FATAL); } } else { coordidy = 0; } if (num_dim > 2) { if ((status = nc_inq_varid (exoid, VAR_COORD_Z, &coordidz)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate z nodal coordinates in file id %d", exoid); ex_err("ex_get_coord",errmsg,exerrval); return (EX_FATAL); } } else { coordidz = 0; } /* write out the coordinates */ for (i=0; i /* for free() */ /*! * writes out the element numbering map to the database; this allows * element numbers to be non-contiguous * \param exoid exodus file id * \param elem_map element numbering map array * \deprecated Use ex_put_id_map()(exoid, EX_ELEM_MAP, elem_map) */ int ex_put_elem_num_map (int exoid, const int *elem_map) { return ex_put_id_map(exoid, EX_ELEM_MAP, elem_map); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expmap.c0000755000175000017500000001121511606020250022247 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expmap - ex_put_map * * entry conditions - * input parameters: * int exoid exodus file id * int* elem_map element order map array * * exit conditions - * * revision history - * * $Id: expmap.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /* for free() */ /*! * writes out the element order map to the database. * \param exoid exodus file id * \param elem_map element order map array * \deprecated Use ex_put_num_map() instead. */ int ex_put_map (int exoid, const int *elem_map) { int numelemdim, dims[1], mapid, status; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire id's of previously defined dimensions */ /* determine number of elements. Return if zero... */ if (nc_inq_dimid(exoid, DIM_NUM_ELEM, &numelemdim) != NC_NOERR) { return (EX_NOERR); } /* put netcdf file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_map",errmsg,exerrval); return (EX_FATAL); } /* create a variable array in which to store the element map */ dims[0] = numelemdim; if ((status = nc_def_var(exoid, VAR_MAP, NC_INT, 1, dims, &mapid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: element map already exists in file id %d", exoid); ex_err("ex_put_map",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to create element map array in file id %d", exoid); ex_err("ex_put_map",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete definition in file id %d", exoid); ex_err("ex_put_map",errmsg,exerrval); return (EX_FATAL); } /* write out the element order map */ status = nc_put_var_int(exoid, mapid, elem_map); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store element map in file id %d", exoid); ex_err("ex_put_map",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_map",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgsstt.c0000644000175000017500000000541011606020250022453 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvtt - ex_get_sset_var_tab * * entry conditions - * input parameters: * int exoid exodus file id * int num_sidesets number of sidesets * int num_sset_var number of sideset variables * * exit conditions - * int* sset_var_tab sideset variable truth table array * * $Id: exgsstt.c,v 1.1 2010-01-06 16:33:37 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * reads the EXODUS II sideset variable truth table from the database * \deprecated Use ex_get_truth_table()(exoid, EX_SIDE_SET, num_sidesets, num_sset_var, sset_var_tab) */ int ex_get_sset_var_tab (int exoid, int num_sidesets, int num_sset_var, int *sset_var_tab) { return ex_get_truth_table(exoid, EX_SIDE_SET, num_sidesets, num_sset_var, sset_var_tab); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvar.c0000644000175000017500000002741311606020250022266 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvar - ex_put_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step time step number * int var_type type (edge block, face block, edge set, ... ) * int var_index element variable index * int obj_id element block id * int num_entries_this_obj number of entries in this block/set * * exit conditions - * * * exit conditions - * * revision history - * * $Id: expvar.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of a single variable for one block at one time * step to the database; assume the first time step and variable index * are 1 * \param exoid exodus file id * \param time_step time step number * \param var_type type (edge block, face block, edge set, ... ) * \param var_index element variable index * \param obj_id element block id * \param num_entries_this_obj number of entries in this block/set * \param var_vals the values to be written */ int ex_put_var (int exoid, int time_step, ex_entity_type var_type, int var_index, int obj_id, int num_entries_this_obj, const void *var_vals) { int varid, dimid,time_dim, numobjdim, dims[2], obj_id_ndx; size_t num_obj; size_t num_obj_var; size_t num_entity; size_t start[2], count[2]; int *obj_var_truth_tab; int status; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ #define EX_LOOK_UP_VAR(VOBJID,VVAR,VOBJTAB,DNUMOBJ,DNUMOBJVAR) \ /* Determine index of obj_id in VOBJID array */ \ obj_id_ndx = ex_id_lkup(exoid,var_type,obj_id); \ if (exerrval != 0) \ { \ if (exerrval == EX_NULLENTITY) \ { \ sprintf(errmsg, \ "Warning: no variables allowed for NULL block %d in file id %d", \ obj_id,exoid); \ ex_err("ex_put_var",errmsg,EX_MSG); \ return (EX_WARN); \ } \ else \ { \ sprintf(errmsg, \ "Error: failed to locate %s id %d in %s array in file id %d", \ ex_name_of_object(var_type), obj_id, VOBJID, exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ return (EX_FATAL); \ } \ } \ \ if ((status = nc_inq_varid (exoid, VVAR(var_index,obj_id_ndx), &varid)) != NC_NOERR) \ { \ if (status == NC_ENOTVAR) /* variable doesn't exist, create it! */ \ { \ /* check for the existance of an TNAME variable truth table */ \ if (nc_inq_varid(exoid, VOBJTAB, &varid) == NC_NOERR) { \ /* find out number of TNAMEs and TNAME variables */ \ status = ex_get_dimension(exoid, DNUMOBJ, ex_name_of_object(var_type), &num_obj, &dimid, "ex_put_var"); \ if (status != NC_NOERR) return status; \ \ status = ex_get_dimension(exoid, DNUMOBJVAR, ex_name_of_object(var_type), &num_obj_var, &dimid, "ex_put_var"); \ if (status != NC_NOERR) return status; \ \ if (!(obj_var_truth_tab = malloc(num_obj*num_obj_var*sizeof(int)))) \ { \ exerrval = EX_MEMFAIL; \ sprintf(errmsg, \ "Error: failed to allocate memory for %s variable truth table in file id %d", \ ex_name_of_object(var_type), exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ /* read in the TNAME variable truth table */ \ if ((status = nc_get_var_int (exoid, varid, obj_var_truth_tab)) != NC_NOERR) \ { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to get truth table from file id %d", exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ if(obj_var_truth_tab[num_obj_var*(obj_id_ndx-1)+var_index-1] \ == 0L) \ { \ free(obj_var_truth_tab); \ exerrval = EX_BADPARAM; \ sprintf(errmsg, \ "Error: Invalid %s variable %d, %s %d in file id %d", \ ex_name_of_object(var_type), var_index, ex_name_of_object(var_type), obj_id, exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ return (EX_FATAL); \ } \ free(obj_var_truth_tab); \ } \ \ if ((status = nc_inq_dimid(exoid, DIM_TIME, &time_dim)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to locate time dimension in file id %d", exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ \ ex_get_dimension(exoid, ex_dim_num_entries_in_object(var_type, obj_id_ndx), \ ex_name_of_object(var_type), &num_entity, &numobjdim, "ex_put_var"); \ \ /* variable doesn't exist so put file into define mode */ \ if ((status = nc_redef (exoid)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to put file id %d into define mode", exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ return (EX_FATAL); \ } \ \ /* define netCDF variable to store TNAME variable values */ \ dims[0] = time_dim; \ dims[1] = numobjdim; \ if ((status = nc_def_var(exoid, VVAR(var_index,obj_id_ndx), \ nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) \ { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define %s variable %d in file id %d", \ ex_name_of_object(var_type), var_index,exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ goto error_ret; \ } \ \ /* leave define mode */ \ \ if ((status = nc_enddef (exoid)) != NC_NOERR) \ { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to complete %s variable %s definition to file id %d", \ ex_name_of_object(var_type), VVAR(var_index,obj_id_ndx), exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ return (EX_FATAL); \ } \ } \ else \ { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to locate %s variable %s in file id %d", \ ex_name_of_object(var_type), VVAR(var_index,obj_id_ndx),exoid); \ ex_err("ex_put_var",errmsg,exerrval); \ return (EX_FATAL); \ } \ } switch (var_type) { case EX_GLOBAL: if ( num_entries_this_obj <= 0 ) { exerrval = EX_MSG; sprintf(errmsg, "Warning: no global variables specified for file id %d", exoid); ex_err("ex_put_glob_vars",errmsg,exerrval); return (EX_WARN); } /* inquire previously defined variable */ if ((status = nc_inq_varid (exoid, VAR_GLO_VAR, &varid)) != NC_NOERR) { if (status == NC_ENOTVAR) { exerrval = status; sprintf(errmsg, "Error: no global variables defined in file id %d", exoid); ex_err("ex_put_glob_vars",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to get global variables parameters in file id %d", exoid); ex_err("ex_put_glob_vars",errmsg,exerrval); } return (EX_FATAL); } break; case EX_NODAL: return ex_put_nodal_var(exoid, time_step, var_index, num_entries_this_obj, var_vals); break; case EX_EDGE_BLOCK: EX_LOOK_UP_VAR(VAR_ID_ED_BLK,VAR_EDGE_VAR,VAR_EBLK_TAB,DIM_NUM_ED_BLK,DIM_NUM_EDG_VAR); break; case EX_FACE_BLOCK: EX_LOOK_UP_VAR(VAR_ID_FA_BLK,VAR_FACE_VAR,VAR_FBLK_TAB,DIM_NUM_FA_BLK,DIM_NUM_FAC_VAR); break; case EX_ELEM_BLOCK: EX_LOOK_UP_VAR(VAR_ID_EL_BLK,VAR_ELEM_VAR,VAR_ELEM_TAB,DIM_NUM_EL_BLK,DIM_NUM_ELE_VAR); break; case EX_NODE_SET: EX_LOOK_UP_VAR(VAR_NS_IDS,VAR_NS_VAR,VAR_NSET_TAB,DIM_NUM_NS,DIM_NUM_NSET_VAR); break; case EX_EDGE_SET: EX_LOOK_UP_VAR(VAR_ES_IDS,VAR_ES_VAR,VAR_ESET_TAB,DIM_NUM_ES,DIM_NUM_ESET_VAR); break; case EX_FACE_SET: EX_LOOK_UP_VAR(VAR_FS_IDS,VAR_FS_VAR,VAR_FSET_TAB,DIM_NUM_FS,DIM_NUM_FSET_VAR); break; case EX_SIDE_SET: EX_LOOK_UP_VAR(VAR_SS_IDS,VAR_SS_VAR,VAR_SSET_TAB,DIM_NUM_SS,DIM_NUM_SSET_VAR); break; case EX_ELEM_SET: EX_LOOK_UP_VAR(VAR_ELS_IDS,VAR_ELS_VAR,VAR_ELSET_TAB,DIM_NUM_ELS,DIM_NUM_ELSET_VAR); break; default: exerrval = EX_MSG; sprintf( errmsg, "Error: invalid variable type (%d) specified for file id %d", var_type, exoid ); ex_err( "ex_put_var", errmsg, exerrval ); return (EX_FATAL); } /* store element variable values */ start[0] = --time_step; start[1] = 0; if ( var_type == EX_GLOBAL ) { /* global variables may be written * - all at once (by setting var_index to 1 and num_entries_this_obj to num_glob, or * - one at a time (by setting var_index to the desired index and num_entries_this_obj to 1. */ count[0] = var_index; } else { count[0] = 1; } count[1] = num_entries_this_obj; if (ex_comp_ws(exoid) == 4) { status = nc_put_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_put_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s %d variable %d in file id %d", ex_name_of_object(var_type), obj_id, var_index,exoid); ex_err("ex_put_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_var",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expatn.c0000644000175000017500000001630611606020250022257 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expatn - ex_put_attr_names * * entry conditions - * input parameters: * int exoid exodus file id * int blk_type block type (edge, face, elem) * int blk_id block id * char* names ptr to array of attribute names * * exit conditions - * * revision history - * * $Id: expatn.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the attribute names for a block * \param exoid exodus file id * \param blk_type block type (edge, face, elem) * \param blk_id block id * \param names ptr to array of attribute names */ int ex_put_attr_names(int exoid, ex_entity_type blk_type, int blk_id, char* names[]) { int status; int varid, numattrdim, blk_id_ndx; size_t num_attr, start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; size_t i; exerrval = 0; /* clear error code */ blk_id_ndx = ex_id_lkup(exoid, blk_type, blk_id); /* Determine index of blk_id in blk_id_ndx array */ if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes allowed for NULL %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_attr_names",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this block */ } else { sprintf(errmsg, "Error: no %s id %d in %s array in file id %d", ex_name_of_object(blk_type), blk_id, VAR_ID_EL_BLK, exoid); ex_err("ex_put_attr_names",errmsg,exerrval); return (EX_FATAL); } } /* inquire id's of previously defined dimensions */ switch (blk_type) { case EX_SIDE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_SS(blk_id_ndx), &numattrdim); break; case EX_NODE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_NS(blk_id_ndx), &numattrdim); break; case EX_EDGE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_ES(blk_id_ndx), &numattrdim); break; case EX_FACE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_FS(blk_id_ndx), &numattrdim); break; case EX_ELEM_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_ELS(blk_id_ndx), &numattrdim); break; case EX_NODAL: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_NBLK, &numattrdim); break; case EX_EDGE_BLOCK: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_EBLK(blk_id_ndx), &numattrdim); break; case EX_FACE_BLOCK: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_FBLK(blk_id_ndx), &numattrdim); break; case EX_ELEM_BLOCK: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_BLK(blk_id_ndx), &numattrdim); break; default: sprintf(errmsg, "Error: called with invalid blk_type %d", blk_type); ex_err("ex_put_attr_names",errmsg,exerrval); return (EX_FATAL); break; } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: number of attributes not defined for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_attr_names",errmsg,EX_MSG); return (EX_FATAL); /* number of attributes not defined */ } if ((status = nc_inq_dimlen(exoid, numattrdim, &num_attr)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of attributes for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_attr_names",errmsg,exerrval); return (EX_FATAL); } switch (blk_type) { case EX_SIDE_SET: status = nc_inq_varid (exoid, VAR_NAME_SSATTRIB(blk_id_ndx), &varid); break; case EX_NODE_SET: status = nc_inq_varid (exoid, VAR_NAME_NSATTRIB(blk_id_ndx), &varid); break; case EX_EDGE_SET: status = nc_inq_varid (exoid, VAR_NAME_ESATTRIB(blk_id_ndx), &varid); break; case EX_FACE_SET: status = nc_inq_varid (exoid, VAR_NAME_FSATTRIB(blk_id_ndx), &varid); break; case EX_ELEM_SET: status = nc_inq_varid (exoid, VAR_NAME_ELSATTRIB(blk_id_ndx), &varid); break; case EX_NODAL: status = nc_inq_varid (exoid, VAR_NAME_NATTRIB, &varid); break; case EX_EDGE_BLOCK: status = nc_inq_varid (exoid, VAR_NAME_EATTRIB(blk_id_ndx), &varid); break; case EX_FACE_BLOCK: status = nc_inq_varid (exoid, VAR_NAME_FATTRIB(blk_id_ndx), &varid); break; case EX_ELEM_BLOCK: status = nc_inq_varid (exoid, VAR_NAME_ATTRIB(blk_id_ndx), &varid); break; default: /* handled above */ break; } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s attribute names for %s %d in file id %d", ex_name_of_object(blk_type),ex_name_of_object(blk_type),blk_id, exoid); ex_err("ex_put_attr_names",errmsg,exerrval); return (EX_FATAL); } /* write out the attributes */ for (i = 0; i < num_attr; i++) { start[0] = i; start[1] = 0; count[0] = 1; count[1] = strlen(names[i])+1; if ((status = nc_put_vara_text(exoid, varid, start, count, (void*) names[i])) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put attribute namess for %s %d in file id %d", ex_name_of_object(blk_type),blk_id,exoid); ex_err("ex_put_attr_names",errmsg,exerrval); return (EX_FATAL); } } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expsp.c0000755000175000017500000000621311606020250022116 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expsp - ex_put_side_set_param * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * int num_side_in_set number of sides in the side set * int num_dist_fact_in_set number of distribution factors in the * side set * * exit conditions - * * revision history - * * $Id: expsp.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the side set id and the number of sides (edges or faces) * which describe a single side set * \param exoid exodus file id * \param side_set_id side set id * \param num_side_in_set number of sides in the side set * \param num_dist_fact_in_set number of distribution factors in the side set * \deprecated Use ex_put_set_param()(exoid, EX_SIDE_SET, side_set_id, num_side_in_set, num_dist_fact_in_set) */ int ex_put_side_set_param (int exoid, int side_set_id, int num_side_in_set, int num_dist_fact_in_set) { return ex_put_set_param(exoid, EX_SIDE_SET, side_set_id, num_side_in_set, num_dist_fact_in_set); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/ex_conv.c0000755000175000017500000002240111606020250022415 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exutils - exodus utilities * * entry conditions - * * exit conditions - * * revision history - * * $Id: ex_conv.c,v 1.1 2010-01-06 16:33:04 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! \file * this file contains code needed to support the various floating point word * size combinations for computation and i/o that applications might want to * use. See the netcdf documentation for more details on the floating point * conversion capabilities. * * netCDF supports two floating point word sizes for its files: * - NC_FLOAT - 32 bit IEEE * - NC_DOUBLE - 64 bit IEEE * */ #define NC_FLOAT_WORDSIZE 4 #define NC_DOUBLE_WORDSIZE 8 struct file_item { int file_id; nc_type netcdf_type_code; int user_compute_wordsize; struct file_item* next; }; struct file_item* file_list = NULL; #define FIND_FILE(ptr,id) { ptr = file_list; \ while(ptr) { \ if( ptr->file_id == id ) break; \ ptr = ptr->next; \ } \ } int ex_conv_ini( int exoid, int* comp_wordsize, int* io_wordsize, int file_wordsize ) { char errmsg[MAX_ERR_LENGTH]; struct file_item* new_file; /*! ex_conv_ini() initializes the floating point conversion process. * * \param exoid an integer uniquely identifying the file of interest. * * \param comp_wordsize compute floating point word size in the user's code. * a zero value indicates that the user is requesting the * default float size for the machine. The appropriate * value is chosen and returned in comp_wordsize, and used * in subsequent conversions. a valid but inappropriate * for this parameter cannot be detected. * * \param io_wordsize the desired floating point word size for a netCDF file. * for an existing file, if this parameter doesn't match * the word size of data already stored in the file, a * fatal error is generated. a value of 0 for an existing * file indicates that the word size of the file was not * known a priori, so use whatever is in the file. a value * of 0 for a new file means to use the default size, an * NC_FLOAT (4 bytes). when a value of 0 is specified the * actual value used is returned in io_wordsize. * * \param file_wordsize floating point word size in an existing netCDF file. * a value of 0 should be passed in for a new netCDF file. * * word size parameters are specified in bytes. valid values are 0, 4, and 8: */ /* check to make sure machine word sizes aren't weird */ if ((sizeof(float) != 4 && sizeof(float) != 8) || (sizeof(double) != 4 && sizeof(double) != 8 ) ) { sprintf(errmsg,"Error: unsupported compute word size for file id: %d", exoid); ex_err("ex_conv_ini",errmsg,EX_FATAL); return(EX_FATAL); } /* check to see if requested word sizes are valid */ if (!*io_wordsize ) { if (!file_wordsize ) *io_wordsize = NC_FLOAT_WORDSIZE; else *io_wordsize = file_wordsize; } else if (*io_wordsize != 4 && *io_wordsize != 8 ) { sprintf(errmsg,"Error: unsupported I/O word size for file id: %d",exoid); ex_err("ex_conv_ini",errmsg,EX_FATAL); return(EX_FATAL); } else if (file_wordsize && *io_wordsize != file_wordsize ) { *io_wordsize = file_wordsize; sprintf(errmsg, "Error: invalid I/O word size specified for existing file id: %d", exoid); ex_err("ex_conv_ini",errmsg,EX_MSG); ex_err("ex_conv_ini", " Requested I/O word size overridden.", EX_MSG); } if (!*comp_wordsize ) { *comp_wordsize = sizeof(float); } else if (*comp_wordsize != 4 && *comp_wordsize != 8 ) { ex_err("ex_conv_ini","Error: invalid compute wordsize specified",EX_FATAL); return(EX_FATAL); } new_file = malloc(sizeof(struct file_item)); new_file->file_id = exoid; new_file->user_compute_wordsize = *comp_wordsize; new_file->next = file_list; file_list = new_file; if (*io_wordsize == NC_FLOAT_WORDSIZE) new_file->netcdf_type_code = NC_FLOAT; else new_file->netcdf_type_code = NC_DOUBLE; return(EX_NOERR); } /*............................................................................*/ /*............................................................................*/ void ex_conv_exit( int exoid ) { /*! ex_conv_exit() takes the structure identified by "exoid" out of the linked * list which describes the files that ex_conv_array() knows how to convert. * * \note it is absolutely necessary for ex_conv_exit() to be called after * ncclose(), if the parameter used as "exoid" is the id returned from * an ncopen() or nccreate() call, as netCDF reuses file ids! * the best place to do this is ex_close(), which is where I did it. * * \param exoid integer which uniquely identifies the file of interest. */ char errmsg[MAX_ERR_LENGTH]; struct file_item* file = file_list; struct file_item* prev = NULL; exerrval = 0; /* clear error code */ while( file ) { if (file->file_id == exoid ) break; prev = file; file = file->next; } if (!file ) { sprintf(errmsg,"Warning: failure to clear file id %d - not in list.",exoid); ex_err("ex_conv_exit",errmsg,EX_MSG); exerrval = EX_BADFILEID; return; } if (prev ) prev->next = file->next; else file_list = file->next; free( file ); } /*............................................................................*/ /*............................................................................*/ nc_type nc_flt_code( int exoid ) { /* nc_flt_code() returns either NC_FLOAT or NC_DOUBLE, based on the parameters * with which ex_conv_ini() was called. nc_flt_code() is used as the nc_type * parameter on ncvardef() calls that define floating point variables. * * "exoid" is some integer which uniquely identifies the file of interest. */ char errmsg[MAX_ERR_LENGTH]; struct file_item* file; exerrval = 0; /* clear error code */ FIND_FILE( file, exoid ); if (!file ) { exerrval = EX_BADFILEID; sprintf(errmsg,"Error: unknown file id %d for nc_flt_code().",exoid); ex_err("nc_flt_code",errmsg,exerrval); return (nc_type) -1; } return file->netcdf_type_code; } int ex_comp_ws( int exoid ) { /*! * ex_comp_ws() returns 4 (i.e. sizeof(float)) or 8 (i.e. sizeof(double)), * depending on the value of floating point word size used to initialize * the conversion facility for this file id (exoid). * \param exoid integer which uniquely identifies the file of interest. */ char errmsg[MAX_ERR_LENGTH]; struct file_item* file; exerrval = 0; /* clear error code */ FIND_FILE( file, exoid ); if (!file ) { exerrval = EX_BADFILEID; sprintf(errmsg,"Error: unknown file id %d",exoid); ex_err("ex_comp_ws",errmsg,exerrval); return(EX_FATAL); } return file->user_compute_wordsize; } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgssvid.c0000644000175000017500000000470511606020250022614 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnsvid - ex_get_sset_varid * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int* varid variable id array * * revision history - * * $Id: exgssvid.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * reads the EXODUS II variable varids from the database * \deprecated Use ex_get_varid()(exoid, EX_SIDE_SET, varid) */ int ex_get_sset_varid (int exoid, int *varid) { return ex_get_varid(exoid, EX_SIDE_SET, varid); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/COPYRIGHT0000755000175000017500000000316311606020250022107 0ustar amckinstryamckinstryCopyright (c) 1994,2006 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement retains certain rights in this software. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sandia Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgenm.c0000755000175000017500000000462111606020250022243 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgenm - ex_get_elem_num_map * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * int* elem_map element number map array * * revision history - * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the element numbering map from the database; allows element numbers * to be noncontiguous */ int ex_get_elem_num_map (int exoid, int *elem_map) { return ex_get_id_map(exoid, EX_ELEM_MAP, elem_map); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expelb.c0000755000175000017500000000702111606020250022234 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expelb - ex_put_elem_block: write element block parameters * * entry conditions - * input parameters: * int idexo exodus file id * int elem_blk_id block identifier * char* elem_type element type string * int num_elem_this_blk number of elements in the element blk * int num_nodes_per_elem number of nodes per element block * int num_attr_per_elem number of attributes per element * * exit conditions - * * $Id: expelb.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the parameters used to describe an element block * \param exoid exodus file id * \param elem_blk_id block identifier * \param elem_type element type string * \param num_elem_this_blk number of elements in the element blk * \param num_nodes_per_elem number of nodes per element block * \param num_attr_per_elem number of attributes per element * \deprecated Use ex_put_block()(exoid, EX_ELEM_BLOCK, elem_blk_id, elem_type, num_elem_this_blk, num_nodes_per_elem, 0, 0, num_attr_per_elem) */ int ex_put_elem_block (int exoid, int elem_blk_id, const char *elem_type, int num_elem_this_blk, int num_nodes_per_elem, int num_attr_per_elem) { return ex_put_block( exoid, EX_ELEM_BLOCK, elem_blk_id, elem_type, num_elem_this_blk, num_nodes_per_elem, 0 /*num_edge_per_elem*/, 0 /*num_face_per_elem*/, num_attr_per_elem ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expoea.c0000644000175000017500000000574011606020250022241 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expoea - ex_put_one_elem_attr * * entry conditions - * input parameters: * int exoid exodus file id * int elem_blk_id element block id * int attrib_index index of attribute to write * float* attrib array of attributes * * exit conditions - * * revision history - * 20061003 - David Thompson - moved to ex_put_one_attr * * $Id: expoea.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the specified attribute for an element block * \param exoid exodus file id * \param elem_blk_id element block id * \param attrib_index index of attribute to write * \param attrib array of attributes * \deprecated Use ex_put_one_attr()(exoid, EX_ELEM_BLOCK, elem_blk_id, attrib_index, attrib) */ int ex_put_one_elem_attr (int exoid, int elem_blk_id, int attrib_index, const void *attrib) { return ex_put_one_attr( exoid, EX_ELEM_BLOCK, elem_blk_id, attrib_index, attrib ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/CMakeLists.txt0000755000175000017500000000777211606020250023366 0ustar amckinstryamckinstryPROJECT(vtkExodus2) INCLUDE_REGULAR_EXPRESSION(".*") INCLUDE(CheckIncludeFile) CHECK_INCLUDE_FILE( malloc.h EX_HAVE_MALLOC_H ) SET(EXODUSII_VERSION_MAJOR "2") SET(EXODUSII_VERSION_MINOR "0") SET(EXODUSII_VERSION_PATCH "0") SET(EXODUSII_VERSION "${EXODUSII_VERSION_MAJOR}.${EXODUSII_VERSION_MINOR}") SET(EXODUSII_VERSION_FULL "${EXODUSII_VERSION}.${EXODUSII_VERSION_PATCH}") SET(EXODUSII_BUILD_SHARED_LIBS "${BUILD_SHARED_LIBS}") CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/include/exodusII_cfg.h.in ${CMAKE_CURRENT_BINARY_DIR}/include/exodusII_cfg.h @ONLY IMMEDIATE) INCLUDE_DIRECTORIES( "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_BINARY_DIR}/include" ) SET(cbind_SRCS exclos.c excn2s.c ex_conv.c excopy.c excre.c exerr.c exgatm.c exgcns.c exgcon.c exgcor.c exgcset.c exgcss.c exgean.c exgatn.c exgeat.c exgatt.c exgebi.c exgelb.c exgblk.c exgelc.c exgconn.c exgem.c exgenm.c exgev.c exgvar.c exgevid.c exgevt.c exgvart.c exgfrm.c exggv.c exggvt.c exgids.c exginf.c exgini.c exginix.c exgmap.c exgmp.c exgnam.c exgnams.c exgnm.c exgnnm.c exgnp.c exgns.c exgnsd.c exgnsi.c exgnstt.c exgnsv.c exgnsvid.c exgnv.c exgnvid.c exgnvt.c exgnvv.c exgoea.c exgoatt.c exgotv.c exgpa.c exgp.c exgpem.c exgpn.c exgqa.c exgsnl.c exgsetp.c exgsp.c exgset.c exgss.c exgssc.c exgsetd.c exgssd.c exgssi.c exgssn.c exgsstt.c exgssv.c exgssvid.c exgtim.c exgtt.c exgvan.c exgvid.c exgvnm.c exgvp.c exgvtt.c exgvv.c exinq.c exopen.c exopts.c expatn.c expatt.c expcab.c expclb.c expcns.c expcon.c expconn.c expcor.c expcset.c expcss.c expean.c expeat.c expelb.c expblk.c expelc.c expem.c expenm.c expev.c expfrm.c expgv.c expinf.c expini.c expinix.c expmap.c expmp.c expnam.c expnams.c expnm.c expnmap.c exgnmap.c expnnm.c expnp.c expns.c expnsd.c expnstt.c expnsv.c expnv.c expnvv.c expoea.c expoatt.c exppa.c expp.c exppem.c exppn.c expqa.c expsetp.c expset.c expsetd.c expsp.c expss.c expssd.c expsstt.c expssv.c exptim.c exptt.c expvan.c expvar.c expvnm.c expvpa.c expvpax.c expvp.c expvpc.c expvtt.c expvv.c exupda.c ex_utils.c exgattp.c exgidm.c exgvarnam.c exgvarnams.c exgvarparam.c exgvartab.c expattp.c expidm.c expvarnam.c expvarnams.c expvarparam.c expvartab.c ) IF(APPLE) SET_SOURCE_FILES_PROPERTIES( ex_utils.c PROPERTIES COMPILE_FLAGS -fno-common) ENDIF(APPLE) ADD_LIBRARY(vtkexoIIc ${cbind_SRCS}) TARGET_LINK_LIBRARIES(vtkexoIIc vtkNetCDF) # Apply user-defined properties to the library target. IF(VTK_LIBRARY_PROPERTIES) SET_TARGET_PROPERTIES(vtkexoIIc PROPERTIES ${VTK_LIBRARY_PROPERTIES}) ENDIF(VTK_LIBRARY_PROPERTIES) IF(NOT VTK_INSTALL_BIN_DIR_CM24) SET(VTK_INSTALL_BIN_DIR_CM24 ${CMAKE_INSTALL_PREFIX}/bin) ENDIF(NOT VTK_INSTALL_BIN_DIR_CM24) IF(NOT VTK_INSTALL_LIB_DIR_CM24) SET(VTK_INSTALL_LIB_DIR_CM24 ${CMAKE_INSTALL_PREFIX}/lib) ENDIF(NOT VTK_INSTALL_LIB_DIR_CM24) IF(NOT VTK_INSTALL_INCLUDE_DIR_CM24) SET(VTK_INSTALL_INCLUDE_DIR_CM24 ${CMAKE_INSTALL_PREFIX}/include) ENDIF(NOT VTK_INSTALL_INCLUDE_DIR_CM24) IF(NOT VTK_INSTALL_NO_LIBRARIES) INSTALL(TARGETS vtkexoIIc RUNTIME DESTINATION ${VTK_INSTALL_BIN_DIR_CM24} COMPONENT RuntimeLibraries LIBRARY DESTINATION ${VTK_INSTALL_LIB_DIR_CM24} COMPONENT RuntimeLibraries ARCHIVE DESTINATION ${VTK_INSTALL_LIB_DIR_CM24} COMPONENT Development) ENDIF(NOT VTK_INSTALL_NO_LIBRARIES) IF(NOT VTK_INSTALL_NO_DEVELOPMENT) INSTALL(FILES include/exodusII.h include/exodusII_ext.h include/exodusII_int.h include/vtk_exodus2_mangle.h DESTINATION ${VTK_INSTALL_INCLUDE_DIR_CM24}/vtkexodus2 COMPONENT Development) ENDIF(NOT VTK_INSTALL_NO_DEVELOPMENT) #INCLUDE (${CMAKE_ROOT}/Modules/Dart.cmake) # Turned off until ExoIICTests.cxx problem is fixed. #IF (BUILD_TESTING) # ENABLE_TESTING() # SUBDIRS(test) #ENDIF (BUILD_TESTING) xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expinf.c0000755000175000017500000001265711606020250022261 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expinf - ex_put_info * * entry conditions - * input parameters: * int exoid exodus file id * char* info[] ptr array of info records * * exit conditions - * * revision history - * * $Id: expinf.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes information records to the database * \param exoid exodus file id * \param num_info count of info records to be written. * \param info[] ptr array of info records */ int ex_put_info (int exoid, int num_info, char *info[]) { int status; int i, lindim, num_info_dim, dims[2], varid; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* only do this if there are records */ if (num_info > 0) { /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_LIN, &lindim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get line string length in file id %d", exoid); ex_err("ex_put_info",errmsg,exerrval); return (EX_FATAL); } /* put file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed put file id %d into define mode", exoid); ex_err("ex_put_info",errmsg,exerrval); return (EX_FATAL); } /* define dimensions */ if ((status = nc_def_dim(exoid, DIM_NUM_INFO, num_info, &num_info_dim)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { /* duplicate entry? */ exerrval = status; sprintf(errmsg, "Error: info records already exist in file id %d", exoid); ex_err("ex_put_info",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define number of info records in file id %d", exoid); ex_err("ex_put_info",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } /* define variable */ dims[0] = num_info_dim; dims[1] = lindim; if ((status = nc_def_var(exoid, VAR_INFO, NC_CHAR, 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define info record in file id %d", exoid); ex_err("ex_put_info",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete info record definition in file id %d", exoid); ex_err("ex_put_info",errmsg,exerrval); return (EX_FATAL); } /* write out information records */ for (i=0; i #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of a single sideset variable for one sideset at * one time step to the database; assume the first time step and * sideset variable index are 1 * \param exoid exodus file id * \param time_step time step number * \param sset_var_index sideset variable index * \param sset_id sideset id * \param num_faces_this_sset number of faces in this sideset * \param sset_var_vals the variable values to be written * \deprecated Use ex_put_var()(exoid, time_step, EX_SIDE_SET, sset_var_index, sset_id, num_faces_this_sset, sset_var_vals) */ int ex_put_sset_var (int exoid, int time_step, int sset_var_index, int sset_id, int num_faces_this_sset, const void *sset_var_vals) { return ex_put_var(exoid, time_step, EX_SIDE_SET, sset_var_index, sset_id, num_faces_this_sset, sset_var_vals); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgsp.c0000755000175000017500000000620211606020250022103 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgsp - ex_get_side_set_param * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * * exit conditions - * int* num_side_in_set number of sides in the side set * int* num_dist_fact_in_set number of distribution factors in the * side set * * revision history - * * $Id: exgsp.c,v 1.1 2010-01-06 16:33:36 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" /*! * reads the number of sides and the number of distribution factors which * describe a single side set * \param exoid exodus file id * \param side_set_id side set id * \param[out] num_side_in_set number of sides in the side set * \param[out] num_dist_fact_in_set number of distribution factors in the * \deprecated Use ex_get_set_param()(exoid, EX_SIDE_SET, side_set_id, num_side_in_set, num_dist_fact_in_set) */ int ex_get_side_set_param (int exoid, int side_set_id, int *num_side_in_set, int *num_dist_fact_in_set) { return ex_get_set_param(exoid, EX_SIDE_SET, side_set_id, num_side_in_set, num_dist_fact_in_set); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvpa.c0000644000175000017500000001022711606020250022257 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvp - ex_put_all_var_param * * entry conditions - * input parameters: * int exoid exodus file id * int num_g global variable count * int num_n nodal variable count * int num_e element variable count * int* elem_var_tab element variable truth table array * int num_m nodeset variable count * int* nset_var_tab nodeset variable truth table array * int num_s sideset variable count * int* sset_var_tab sideset variable truth table array * * exit conditions - * * $Id: expvpa.c,v 1.1 2010-01-06 16:33:44 kwleiter Exp $ *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * defines the number of global, nodal, element, nodeset, and sideset variables * that will be written to the database * \param exoid exodus file id * \param num_g global variable count * \param num_n nodal variable count * \param num_e element variable count * \param *elem_var_tab element variable truth table array * \param num_m nodeset variable count * \param *nset_var_tab nodeset variable truth table array * \param num_s sideset variable count * \param *sset_var_tab sideset variable truth table array */ int ex_put_all_var_param (int exoid, int num_g, int num_n, int num_e, int *elem_var_tab, int num_m, int *nset_var_tab, int num_s, int *sset_var_tab) { ex_var_params vparam; vparam.num_glob = num_g; vparam.num_node = num_n; vparam.num_edge = 0; vparam.edge_var_tab = 0; vparam.num_face = 0; vparam.face_var_tab = 0; vparam.num_elem = num_e; vparam.elem_var_tab = elem_var_tab; vparam.num_nset = num_m; vparam.nset_var_tab = nset_var_tab; vparam.num_eset = 0; vparam.eset_var_tab = 0; vparam.num_fset = 0; vparam.fset_var_tab = 0; vparam.num_sset = num_s; vparam.sset_var_tab = sset_var_tab; vparam.num_elset = 0; vparam.elset_var_tab = 0; return ex_put_all_var_param_ext( exoid, &vparam ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnm.c0000755000175000017500000000516111606020250022107 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnm - ex_put_node_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_id node map id * int *node_map node map * * exit conditions - * *****************************************************************************/ #include "exodusII.h" /*! * writes an node map; this is a vector of integers of length number * of nodes * \param exoid exodus file id * \param map_id node map id * \param node_map node map * \deprecated Use ex_put_num_map()(exoid, EX_NODE_MAP, map_id, node_map) */ int ex_put_node_map (int exoid, int map_id, const int *node_map) { return ex_put_num_map( exoid, EX_NODE_MAP, map_id, node_map ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvpax.c0000644000175000017500000005136411606020250022456 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvp - ex_put_all_var_param_ext * * entry conditions - * input parameters: * int exoid exodus file id * const ex_var_params* vp pointer to variable parameter info * * exit conditions - * * $Id: expvpax.c,v 1.1 2010-01-06 16:33:47 kwleiter Exp $ *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" #include static void *safe_free(void *array); static int define_dimension(int exoid, const char *DIMENSION, int count, const char *label, int *dimid); static int define_variable_name_variable(int exoid, const char *VARIABLE, int dimension, const char *label); static int *get_status_array(int exoid, int count, const char *VARIABLE, const char *label); static int put_truth_table(int exoid, int varid, int *table, const char *label); static int define_truth_table(ex_entity_type obj_type, int exoid, int num_ent, int num_var, int *var_tab, int *status, int *ids, const char *label); #define EX_GET_IDS_STATUS(TNAME,NUMVAR,DNAME,DID,DVAL,VIDS,EIDS,VSTAT,VSTATVAL) \ if (NUMVAR > 0) { \ status = ex_get_dimension(exoid, DNAME, TNAME "s", &DVAL, &DID, routine); \ if (status != NC_NOERR) \ goto error_ret; \ \ /* get element block IDs */ \ if (!(VIDS = malloc(DVAL*sizeof(int)))) { \ exerrval = EX_MEMFAIL; \ sprintf(errmsg, \ "Error: failed to allocate memory for " TNAME " id array for file id %d", \ exoid); \ ex_err("ex_put_all_var_param_ext",errmsg,exerrval); \ goto error_ret; \ } \ ex_get_ids (exoid, EIDS, VIDS); \ \ /* Get element block status array for later use (allocates memory) */ \ VSTATVAL = get_status_array(exoid, DVAL, VSTAT, TNAME); \ if (VSTATVAL == NULL) { \ goto error_ret; \ } \ } /*! * writes the number of global, nodal, element, nodeset, and sideset variables * that will be written to the database * \param exoid exodus file id * \param *vp pointer to variable parameter info */ int ex_put_all_var_param_ext ( int exoid, const ex_var_params* vp ) { int in_define = 0; int status; int temp; int time_dim, num_nod_dim, dimid; size_t num_elem_blk, num_edge_blk, num_face_blk; size_t num_nset, num_eset, num_fset, num_sset, num_elset; int numelblkdim, numelvardim, numedvardim, numedblkdim, numfavardim, numfablkdim, numnsetdim, nsetvardim, numesetdim, esetvardim, numfsetdim, fsetvardim, numssetdim, ssetvardim, numelsetdim, elsetvardim; int i; int edblk_varid, fablk_varid, eblk_varid, nset_varid, eset_varid, fset_varid, sset_varid, elset_varid, varid; int* eblk_ids = 0; int* edblk_ids = 0; int* fablk_ids = 0; int* nset_ids = 0; int* eset_ids = 0; int* fset_ids = 0; int* sset_ids = 0; int* elset_ids = 0; int* eblk_stat = 0; int* edblk_stat = 0; int* fablk_stat = 0; int* nset_stat = 0; int* eset_stat = 0; int* fset_stat = 0; int* sset_stat = 0; int* elset_stat = 0; int dims[3]; char errmsg[MAX_ERR_LENGTH]; const char* routine = "ex_put_all_var_param_ext"; exerrval = 0; /* clear error code */ /* inquire previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_TIME, &time_dim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate time dimension in file id %d", exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); goto error_ret; } if ((status = nc_inq_dimid (exoid, DIM_NUM_NODES, &num_nod_dim)) != NC_NOERR) { if (vp->num_node > 0) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of nodes in file id %d", exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); goto error_ret; } } /* Check this now so we can use it later without checking for errors */ if ((status = nc_inq_dimid(exoid, DIM_STR, &temp)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); goto error_ret; } EX_GET_IDS_STATUS( "edge block",vp->num_edge, DIM_NUM_ED_BLK,numedblkdim,num_edge_blk,edblk_ids,EX_EDGE_BLOCK,VAR_STAT_ED_BLK,edblk_stat); EX_GET_IDS_STATUS( "face block",vp->num_face, DIM_NUM_FA_BLK,numfablkdim,num_face_blk,fablk_ids,EX_FACE_BLOCK,VAR_STAT_FA_BLK,fablk_stat); EX_GET_IDS_STATUS("element block",vp->num_elem, DIM_NUM_EL_BLK,numelblkdim,num_elem_blk, eblk_ids,EX_ELEM_BLOCK,VAR_STAT_EL_BLK, eblk_stat); EX_GET_IDS_STATUS( "node set",vp->num_nset, DIM_NUM_NS, numnsetdim, num_nset, nset_ids,EX_NODE_SET, VAR_NS_STAT, nset_stat); EX_GET_IDS_STATUS( "edge set",vp->num_eset, DIM_NUM_ES, numesetdim, num_eset, eset_ids,EX_EDGE_SET, VAR_ES_STAT, eset_stat); EX_GET_IDS_STATUS( "face set",vp->num_fset, DIM_NUM_FS, numfsetdim, num_fset, fset_ids,EX_FACE_SET, VAR_FS_STAT, fset_stat); EX_GET_IDS_STATUS( "side set",vp->num_sset, DIM_NUM_SS, numssetdim, num_sset, sset_ids,EX_SIDE_SET, VAR_SS_STAT, sset_stat); EX_GET_IDS_STATUS( "element set",vp->num_elset,DIM_NUM_ELS, numelsetdim,num_elset, elset_ids,EX_ELEM_SET, VAR_ELS_STAT, elset_stat); /* put file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); goto error_ret; } in_define = 1; /* define dimensions and variables */ if (vp->num_glob > 0) { if (define_dimension(exoid, DIM_NUM_GLO_VAR, vp->num_glob, "global", &dimid) != NC_NOERR) goto error_ret; dims[0] = time_dim; dims[1] = dimid; if ((status = nc_def_var (exoid, VAR_GLO_VAR, nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define global variables in file id %d", exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* Now define global variable name variable */ if (define_variable_name_variable(exoid, VAR_NAME_GLO_VAR, dimid, "global") != NC_NOERR) goto error_ret; } if (vp->num_node > 0) { /* * There are two ways to store the nodal variables. The old way * * was a blob (#times,#vars,#nodes), but that was exceeding the * netcdf maximum dataset size for large models. The new way is * to store #vars separate datasets each of size (#times,#nodes) * * We want this routine to be capable of storing both formats * based on some external flag. Since the storage format of the * coordinates have also been changed, we key off of their * storage type to decide which method to use for nodal * variables. If the variable 'coord' is defined, then store old * way; otherwise store new. */ if (define_dimension(exoid, DIM_NUM_NOD_VAR, vp->num_node, "nodal", &dimid) != NC_NOERR) goto error_ret; if (ex_large_model(exoid) == 0) { /* Old way */ dims[0] = time_dim; dims[1] = dimid; dims[2] = num_nod_dim; if ((status = nc_def_var(exoid, VAR_NOD_VAR, nc_flt_code(exoid), 3, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define nodal variables in file id %d", exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } else { /* Store new way */ for (i = 1; i <= vp->num_node; i++) { dims[0] = time_dim; dims[1] = num_nod_dim; if ((status = nc_def_var(exoid, VAR_NOD_VAR_NEW(i), nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define nodal variable %d in file id %d", i, exoid); ex_err("ex_put_var_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } /* Now define nodal variable name variable */ if (define_variable_name_variable(exoid, VAR_NAME_NOD_VAR, dimid, "nodal") != NC_NOERR) goto error_ret; } #define EX_DEFINE_VARS(TID,STNAME,TNAME,NUMVAR,DNAME,DID1,DID2,DVAL,VIDS,VNOV,VTV,VSTATVAL,VTABVAL,VTABVAR) \ if (NUMVAR > 0) { \ status = define_dimension(exoid, DNAME, NUMVAR, STNAME, &DID2); \ if (status != NC_NOERR) goto error_ret; \ \ /* Now define STNAME variable name variable */ \ if (define_variable_name_variable(exoid, VNOV, DID2, STNAME) != NC_NOERR) \ goto error_ret; \ \ if (define_truth_table(TID, exoid, DVAL, NUMVAR, VTABVAL, VSTATVAL, VIDS, TNAME) != NC_NOERR) \ goto error_ret; \ \ VSTATVAL = safe_free (VSTATVAL); \ VIDS = safe_free (VIDS); \ \ /* create a variable array in which to store the STNAME variable truth \ * table \ */ \ \ dims[0] = DID1; \ dims[1] = DID2; \ \ if ((status = nc_def_var(exoid, VTV, NC_INT, 2, dims, &VTABVAR)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, \ "Error: failed to define " STNAME " variable truth table in file id %d", \ exoid); \ ex_err("ex_put_all_var_param_ext",errmsg,exerrval); \ goto error_ret; /* exit define mode and return */ \ } \ } EX_DEFINE_VARS(EX_EDGE_BLOCK, "edge", "edge block",vp->num_edge, DIM_NUM_EDG_VAR, numedblkdim,numedvardim,num_edge_blk,edblk_ids,VAR_NAME_EDG_VAR, VAR_EBLK_TAB, edblk_stat,vp->edge_var_tab,edblk_varid); EX_DEFINE_VARS(EX_FACE_BLOCK, "face", "face block",vp->num_face, DIM_NUM_FAC_VAR, numfablkdim,numfavardim,num_face_blk,fablk_ids,VAR_NAME_FAC_VAR, VAR_FBLK_TAB, fablk_stat,vp->face_var_tab,fablk_varid); EX_DEFINE_VARS(EX_ELEM_BLOCK,"element","element block",vp->num_elem, DIM_NUM_ELE_VAR, numelblkdim,numelvardim,num_elem_blk, eblk_ids,VAR_NAME_ELE_VAR, VAR_ELEM_TAB, eblk_stat,vp->elem_var_tab,eblk_varid); EX_DEFINE_VARS(EX_NODE_SET, "nodeset", "node set",vp->num_nset, DIM_NUM_NSET_VAR, numnsetdim, nsetvardim, num_nset, nset_ids,VAR_NAME_NSET_VAR, VAR_NSET_TAB, nset_stat,vp->nset_var_tab, nset_varid); EX_DEFINE_VARS(EX_EDGE_SET, "edgeset", "edge set",vp->num_eset, DIM_NUM_ESET_VAR, numesetdim, esetvardim, num_eset, eset_ids,VAR_NAME_ESET_VAR, VAR_ESET_TAB, eset_stat,vp->eset_var_tab, eset_varid); EX_DEFINE_VARS(EX_FACE_SET, "faceset", "face set",vp->num_fset, DIM_NUM_FSET_VAR, numfsetdim, fsetvardim, num_fset, fset_ids,VAR_NAME_FSET_VAR, VAR_FSET_TAB, fset_stat,vp->fset_var_tab, fset_varid); EX_DEFINE_VARS(EX_SIDE_SET, "sideset", "side set",vp->num_sset, DIM_NUM_SSET_VAR, numssetdim, ssetvardim, num_sset, sset_ids,VAR_NAME_SSET_VAR, VAR_SSET_TAB, sset_stat,vp->sset_var_tab, sset_varid); EX_DEFINE_VARS(EX_ELEM_SET, "elemset", "element set",vp->num_elset,DIM_NUM_ELSET_VAR,numelsetdim,elsetvardim,num_elset, elset_ids,VAR_NAME_ELSET_VAR,VAR_ELSET_TAB,elset_stat,vp->elset_var_tab,elset_varid); /* leave define mode */ in_define = 0; if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete definition in file id %d", exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); goto error_ret; } /* write out the variable truth tables */ if (vp->num_edge > 0) { if (put_truth_table(exoid, edblk_varid, vp->edge_var_tab, "edge") != NC_NOERR) goto error_ret; } if (vp->num_face > 0) { if (put_truth_table(exoid, fablk_varid, vp->face_var_tab, "face") != NC_NOERR) goto error_ret; } if (vp->num_elem > 0) { if (put_truth_table(exoid, eblk_varid, vp->elem_var_tab, "element") != NC_NOERR) goto error_ret; } if (vp->num_nset > 0) { if (put_truth_table(exoid, nset_varid, vp->nset_var_tab, "nodeset") != NC_NOERR) goto error_ret; } if (vp->num_eset > 0) { if (put_truth_table(exoid, eset_varid, vp->eset_var_tab, "edgeset") != NC_NOERR) goto error_ret; } if (vp->num_fset > 0) { if (put_truth_table(exoid, fset_varid, vp->fset_var_tab, "faceset") != NC_NOERR) goto error_ret; } if (vp->num_sset > 0) { if (put_truth_table(exoid, sset_varid, vp->sset_var_tab, "sideset") != NC_NOERR) goto error_ret; } if (vp->num_elset > 0) { if (put_truth_table(exoid, elset_varid, vp->elset_var_tab, "elemset") != NC_NOERR) goto error_ret; } return(EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (in_define == 1) { if (nc_enddef (exoid) != NC_NOERR) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); } } safe_free(eblk_ids); safe_free(edblk_ids); safe_free(fablk_ids); safe_free(nset_ids); safe_free(eset_ids); safe_free(fset_ids); safe_free(sset_ids); safe_free(elset_ids); safe_free(eblk_stat); safe_free(edblk_stat); safe_free(fablk_stat); safe_free(nset_stat); safe_free(eset_stat); safe_free(fset_stat); safe_free(sset_stat); safe_free(elset_stat); return(EX_FATAL); } int define_dimension(int exoid, const char *DIMENSION, int count, const char *label, int *dimid) { char errmsg[MAX_ERR_LENGTH]; int status; if ((status = nc_def_dim(exoid, DIMENSION, count, dimid)) != NC_NOERR) { exerrval = status; if (status == NC_ENAMEINUSE) { sprintf(errmsg, "Error: %s variable name parameters are already defined in file id %d", label, exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); } else { sprintf(errmsg, "Error: failed to define number of %s variables in file id %d", label, exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); } } return status; } int define_variable_name_variable(int exoid, const char *VARIABLE, int dimension, const char *label) { char errmsg[MAX_ERR_LENGTH]; int dims[2]; int variable; int status; dims[0] = dimension; nc_inq_dimid(exoid, DIM_STR, &dims[1]); /* Checked earlier, so known to exist */ if ((status=nc_def_var(exoid, VARIABLE, NC_CHAR, 2, dims, &variable)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: %s variable names are already defined in file id %d", label, exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to define %s variable names in file id %d", label, exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); } } return status; } int *get_status_array(int exoid, int var_count, const char *VARIABLE, const char *label) { char errmsg[MAX_ERR_LENGTH]; int varid; int status; int *stat_vals = NULL; if (!(stat_vals = malloc(var_count*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate memory for %s status array for file id %d", label, exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); return (NULL); } /* get variable id of status array */ if ((nc_inq_varid (exoid, VARIABLE, &varid)) == NC_NOERR) { /* if status array exists (V 2.01+), use it, otherwise assume object exists to be backward compatible */ if ((status = nc_get_var_int(exoid, varid, stat_vals)) != NC_NOERR) { exerrval = status; stat_vals = safe_free(stat_vals); sprintf(errmsg, "Error: failed to get %s status array from file id %d", label, exoid); ex_err("ex_put_all_var_param_ext",errmsg,exerrval); return (NULL); } } else { /* status array doesn't exist (V2.00), dummy one up for later checking */ int i; for(i=0; i #include #define EX_PUT_NAMES(TNAME,DNUMVAR,VNAMES) \ if ((status = nc_inq_dimid(exoid, DNUMVAR, &dimid)) != NC_NOERR) { \ exerrval = status; \ if (status == NC_EBADDIM) { \ sprintf(errmsg, \ "Error: no " TNAME " variables defined in file id %d", \ exoid); \ ex_err("ex_put_var_names",errmsg,exerrval); \ } else { \ sprintf(errmsg, \ "Error: failed to locate number of " TNAME " variables in file id %d", \ exoid); \ ex_err("ex_put_var_names",errmsg,exerrval); \ } \ return(EX_FATAL); \ } \ \ if ((status = nc_inq_varid(exoid, VNAMES, &varid)) != NC_NOERR) { \ exerrval = status; \ if (status == NC_ENOTVAR) \ { \ sprintf(errmsg, \ "Error: no " TNAME " variable names defined in file id %d", \ exoid); \ ex_err("ex_put_var_names",errmsg,exerrval); \ } else { \ sprintf(errmsg, \ "Error: " TNAME " name variable names not found in file id %d", \ exoid); \ ex_err("ex_put_var_names",errmsg,exerrval); \ } \ return(EX_FATAL); \ } /*! * writes the names of the results variables to the database * \param exoid exodus file id * \param obj_type variable type * \param num_vars # of variables to read * \param *var_names ptr array of variable names */ int ex_put_variable_names (int exoid, ex_entity_type obj_type, int num_vars, char* var_names[]) { int i, varid, dimid, status; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ switch (obj_type) { case EX_GLOBAL: EX_PUT_NAMES( "global",DIM_NUM_GLO_VAR, VAR_NAME_GLO_VAR); break; case EX_NODAL: EX_PUT_NAMES( "nodal",DIM_NUM_NOD_VAR, VAR_NAME_NOD_VAR); break; case EX_EDGE_BLOCK: EX_PUT_NAMES( "edge",DIM_NUM_EDG_VAR, VAR_NAME_EDG_VAR); break; case EX_FACE_BLOCK: EX_PUT_NAMES( "face",DIM_NUM_FAC_VAR, VAR_NAME_FAC_VAR); break; case EX_ELEM_BLOCK: EX_PUT_NAMES( "element",DIM_NUM_ELE_VAR, VAR_NAME_ELE_VAR); break; case EX_NODE_SET: EX_PUT_NAMES( "node set",DIM_NUM_NSET_VAR, VAR_NAME_NSET_VAR); break; case EX_EDGE_SET: EX_PUT_NAMES( "edge set",DIM_NUM_ESET_VAR, VAR_NAME_ESET_VAR); break; case EX_FACE_SET: EX_PUT_NAMES( "face set",DIM_NUM_FSET_VAR, VAR_NAME_FSET_VAR); break; case EX_SIDE_SET: EX_PUT_NAMES( "side set",DIM_NUM_SSET_VAR, VAR_NAME_SSET_VAR); break; case EX_ELEM_SET: EX_PUT_NAMES("element set",DIM_NUM_ELSET_VAR,VAR_NAME_ELSET_VAR); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid variable type %d specified in file id %d", obj_type, exoid); ex_err("ex_put_var_names",errmsg,exerrval); return(EX_FATAL); } /* write EXODUS variable names */ for (i=0; i /* for free() */ /*! * writes a map; this is a vector of integers of the same length as the * number of entries in the source object (nodes, edges, faces, or elements * in the file). * \param exoid exodus file id * \param map_type type of map (node,edge,face,elem) * \param map_id id to associate with new map * \param map map set value array */ int ex_put_num_map ( int exoid, ex_entity_type map_type, int map_id, const int *map ) { int dimid, varid; size_t start[1]; int ldum; int num_maps; size_t num_entries; int cur_num_maps; char *cdum; char errmsg[MAX_ERR_LENGTH]; const char* dnumentries; const char* dnummaps; const char* vmapids; const char* vmap; int status; exerrval = 0; /* clear error code */ cdum = 0; switch ( map_type ) { case EX_NODE_MAP: dnumentries = DIM_NUM_NODES; dnummaps = DIM_NUM_NM; vmapids = VAR_NM_PROP(1); break; case EX_EDGE_MAP: dnumentries = DIM_NUM_EDGE; dnummaps = DIM_NUM_EDM; vmapids = VAR_EDM_PROP(1); break; case EX_FACE_MAP: dnumentries = DIM_NUM_FACE; dnummaps = DIM_NUM_FAM; vmapids = VAR_FAM_PROP(1); break; case EX_ELEM_MAP: dnumentries = DIM_NUM_ELEM; dnummaps = DIM_NUM_EM; vmapids = VAR_EM_PROP(1); break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Bad map type (%d) specified for file id %d", map_type, exoid ); ex_err( "ex_put_num_map", errmsg, exerrval ); return (EX_FATAL); } /* Make sure the file contains entries */ if (nc_inq_dimid (exoid, dnumentries, &dimid) != NC_NOERR ) { return (EX_NOERR); } /* first check if any maps are specified */ if ((status = nc_inq_dimid (exoid, dnummaps, &dimid)) != NC_NOERR ) { exerrval = status; sprintf(errmsg, "Error: no %ss specified in file id %d", ex_name_of_object(map_type),exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } /* Check for duplicate map id entry */ ex_id_lkup(exoid,map_type,map_id); if (exerrval != EX_LOOKUPFAIL) /* found the map id */ { sprintf(errmsg, "Error: %s %d already defined in file id %d", ex_name_of_object(map_type),map_id,exoid); ex_err("ex_put_num_map",errmsg,exerrval); return(EX_FATAL); } /* Get number of maps initialized for this file */ if ((status = nc_inq_dimlen(exoid,dimid,&num_entries)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of %ss in file id %d", ex_name_of_object(map_type),exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } num_maps = num_entries; /* Keep track of the total number of maps defined using a counter stored in a linked list keyed by exoid. NOTE: ex_get_file_item is used to find the number of maps for a specific file and returns that value. */ cur_num_maps = ex_get_file_item(exoid, ex_get_counter_list(map_type)); if (cur_num_maps >= num_maps) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of %ss (%d) specified in file id %d", ex_name_of_object(map_type),num_maps,exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } /* NOTE: ex_inc_file_item is used to find the number of maps for a specific file and returns that value incremented. */ cur_num_maps = ex_inc_file_item(exoid, ex_get_counter_list(map_type)); /* write out information to previously defined variable */ /* first get id of variable */ if ((status = nc_inq_varid (exoid, vmapids, &varid)) == -1) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s ids in file id %d", ex_name_of_object(map_type),exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } /* then, write out map id */ start[0] = cur_num_maps; ldum = (int)map_id; if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s id %d in file id %d", ex_name_of_object(map_type),map_id,exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } switch ( map_type ) { case EX_NODE_MAP: vmap = VAR_NODE_MAP(cur_num_maps+1); break; case EX_EDGE_MAP: vmap = VAR_EDGE_MAP(cur_num_maps+1); break; case EX_FACE_MAP: vmap = VAR_FACE_MAP(cur_num_maps+1); break; case EX_ELEM_MAP: vmap = VAR_ELEM_MAP(cur_num_maps+1); break; default: sprintf(errmsg, "Error: Called with invalid map_type %d", map_type); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } /* locate variable array in which to store the map */ if ((status = nc_inq_varid(exoid,vmap,&varid)) != NC_NOERR) { int dims[2]; /* determine number of entries */ if ((status = nc_inq_dimid (exoid, dnumentries, &dimid)) == -1 ) { exerrval = status; sprintf(errmsg, "Error: couldn't determine number of %s entries in file id %d", ex_name_of_object(map_type),exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } status = 0; if ((status = nc_redef( exoid )) != NC_NOERR ) { exerrval = status; sprintf(errmsg, "Error: failed to place file id %d into define mode", exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } dims[0] = dimid; if ((status = nc_def_var( exoid, vmap, NC_INT, 1, dims, &varid )) == -1 ) { exerrval = status; sprintf(errmsg, "Error: failed to define map %s in file id %d", vmap, exoid); ex_err("ex_put_num_map",errmsg,exerrval); } if ((status = nc_enddef(exoid)) != NC_NOERR ) { /* exit define mode */ sprintf( errmsg, "Error: failed to complete definition for file id %d", exoid ); ex_err( "ex_put_num_map", errmsg, exerrval ); varid = -1; /* force early exit */ } if ( varid == -1 ) /* we couldn't define variable and have prepared error message. */ return (EX_FATAL); } /* write out the map */ if ((status = nc_put_var_int(exoid, varid, map)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s in file id %d", ex_name_of_object(map_type),exoid); ex_err("ex_put_num_map",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exopts.c0000755000175000017500000000545411606020250022307 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exopts - ex_opts * * entry conditions - * input parameters: * int options error reporting options mask * * exit conditions - * The internal error reporting options mask, exoptval, is set to the passed * value - no error checking is done. * * revision history - * * $Id: exopts.c,v 1.1 2010-01-06 16:33:39 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* init exoptval */ #if defined(VERBOSE) int exoptval = EX_VERBOSE; /* loud mode: set EX_VERBOSE */ #else #if defined (DEBUG) int exoptval = EX_VERBOSE | EX_DEBUG;/* debug mode: set EX_VERBOSE & EX_DEBUG */ #else int exoptval = EX_DEFAULT; /* set default global options value to NOT print error msgs*/ #endif #endif /*! * error reporting options mask * \param options error reporting options mask \sa ex_options */ void ex_opts (int options) { exerrval = 0; /* clear error code */ exoptval = options; ncopts = exoptval; } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/excn2s.c0000755000175000017500000011066011606020250022163 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * excn2s - ex_cvt_nodes_to_sides: convert nodes to sides * * entry conditions - * input parameters: * int exoid exodus file id * int *num_elem_per_set number of element per set * int *num_nodes_per_set number of nodes per set * int *side_sets_elem_index index array of elements into elem list * int *side_sets_node_index index array of nodes * int *side_sets_elem_list array of elements * int *side_sets_node_list array of nodes * * exit conditions - * int *side_sets_side_list array of sides/faces * * revision history - * * $Id: excn2s.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include #include #include #include "exodusII.h" #include "exodusII_int.h" /*! * This routine is designed to take the results from retrieving the ExodusI * style concatenated side sets to the Exodus II V 2.0 definition * uses the element id to get the coordinate node list, element block * connectivity, element type to * convert the side set node list to a side/face list. * \param exoid exodus file id * \param *num_elem_per_set number of element per set * \param *num_nodes_per_set number of nodes per set * \param *side_sets_elem_index index array of elements into elem list * \param *side_sets_node_index index array of nodes * \param *side_sets_elem_list array of elements * \param *side_sets_node_list array of nodes * \param[out] *side_sets_side_list array of sides/faces Algorithm: \verbatim Read elem_block_ids --> elem_blk_id[array] Read element block parameters --> elem_blk_parms[array] Determine total number of elements in side set by summing num_elem_per_set Build side set element to side set node list index --> ss_elem_node_ndx[array] For each element in the side_set_elem_list { If Jth element is not in current element block (e.g. J>elem_ctr) { get element block parameters (num_elem_in_blk, ...) elem_ctr += num_elem_in_blk free old connectity array space allocate connectivity array: size=num_elem_in_blk*num_nodes_per_elem get connectivity array } If Jth element is in current element block (e.g. J<=elem_ctr) { For each node in element (linear search of up to num_nodes_per_elem) { If side set element node[1] == element node[i] { Case element type = Hex { If side set element node[2] == element node[Hex_table[i,1]] Jth side = Hex_table[i,2] break } Case element type = Wedge { If side set element node[2] == element node[Wedge_table[i,1]] Jth side = Wedge_table[i,2] break } } } } } \endverbatim */ int ex_cvt_nodes_to_sides(int exoid, int *num_elem_per_set, int *num_nodes_per_set, int *side_sets_elem_index, int *side_sets_node_index, int *side_sets_elem_list, int *side_sets_node_list, int *side_sets_side_list) { int i, j, k, m, n; int num_side_sets, num_elem_blks; int tot_num_elem = 0, tot_num_ss_elem = 0, elem_num = 0, ndim; int *elem_blk_ids, *connect = 0; int *ss_elem_ndx, *ss_elem_node_ndx, *ss_parm_ndx; int elem_ctr, node_ctr, elem_num_pos; int num_elem_in_blk, num_nodes_per_elem, num_node_per_side, num_attr; int *same_elem_type, el_type = -1; float fdum; char *cdum, elem_type[MAX_STR_LENGTH+1]; struct elem_blk_parm *elem_blk_parms; /* node to side translation tables - These tables are used to look up the side number based on the first and second node in the side/face list. The side node order is found in the original Exodus document, SAND87-2997. The element node order is found in the ExodusII document, SAND92-2137. These tables were generated by following the right-hand rule for determining the outward normal. Note: Only the more complex 3-D shapes require these tables, the simple shapes are trivial - the first node found is also the side number. */ /* 1 2 3 4 node 1 */ static int shell_table[2][8] = { {2,4, 3,1, 4,2, 1,3}, /* node 2 */ {1,2, 1,2, 1,2, 1,2} /* side # */ }; /* 1 2 3 4 node 1 */ static int shell_edge_table[2][8] = { {2,4, 3,1, 4,2, 1,3}, /* node 2 */ {3,6, 4,3, 5,4, 6,5} /* side # */ }; /* 1 2 3 node 1 */ static int trishell_table[2][6] = { {2,3, 3,1, 1,2}, /* node 2 */ {1,2, 1,2, 1,2} /* side # */ }; /* 1 2 3 4 node 1 */ static int tetra_table[2][12] = { {2,3,4, 1,3,4, 4,1,2, 1,2,3}, /* node 2 */ {1,4,3, 4,2,1, 2,3,4, 1,2,3} /* side # */ }; #if 0 static int wedge_table[2][18] = { /* 1 2 3 4 5 6 node 1 */ {2,4,3, 5,1,3, 6,1,2, 1,6,5, 6,2,4, 4,3,5}, /* node 2 */ {1,3,4, 1,4,2, 2,3,4, 1,3,5, 5,2,1, 5,3,2} /* side # */ }; #endif static int hex_table[2][24] = { /* 1 2 3 4 5 6 7 8 node 1 */ {4,2,5, 1,3,6, 7,4,2, 3,1,8, 6,8,1, 5,2,7, 8,6,3, 7,5,4},/* node 2 */ {5,1,4, 5,2,1, 2,3,5, 5,4,3, 6,4,1, 1,2,6, 6,2,3, 3,6,4} /* side # */ }; char errmsg[MAX_ERR_LENGTH]; (void)side_sets_elem_index; (void)side_sets_node_index; exerrval = 0; /* clear error code */ cdum = 0; /* initialize even though it is not used */ /* first check if any side sets are specified */ /* inquire how many side sets have been stored */ if ((ex_inquire(exoid, EX_INQ_SIDE_SETS, &num_side_sets, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of side sets in file id %d",exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); return(EX_FATAL); } if (num_side_sets == 0) { sprintf(errmsg, "Warning: no side sets defined in file id %d",exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,EX_WARN); return(EX_WARN); } if ((ex_inquire(exoid, EX_INQ_ELEM_BLK, &num_elem_blks, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get number of element blocks in file id %d",exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); return(EX_FATAL); } if ((ex_inquire(exoid, EX_INQ_ELEM, &tot_num_elem, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get total number of elements in file id %d",exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); return(EX_FATAL); } /* get the dimensionality of the coordinates; this is necessary to distinguish between 2d TRIs and 3d TRIs */ if ((ex_inquire(exoid, EX_INQ_DIM, &ndim, &fdum, cdum)) == -1) { sprintf(errmsg, "Error: failed to get dimensionality in file id %d",exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); return(EX_FATAL); } /* First count up # of elements in the side sets*/ for (i=0;i= elem_ctr ) { elem_ctr += num_elem_per_set[++k]; el_type = elem_blk_parms[j].elem_type_val; same_elem_type[k] = TRUE; } if (el_type != elem_blk_parms[j].elem_type_val) same_elem_type[k] = FALSE; } /* Build side set element to node list index and side set element parameter index. */ node_ctr = 0; elem_ctr = num_elem_per_set[0]; for (i=0,k=0;i= elem_ctr) { /* skip over NULL side sets */ while (num_elem_per_set[++k] == 0); elem_ctr += num_elem_per_set[k]; } /* determine number of nodes per side */ if (((num_nodes_per_set[k] % num_elem_per_set[k]) == 0) && (same_elem_type[k])) { /* all side set elements are same type */ node_ctr += num_nodes_per_set[k] /num_elem_per_set[k]; } else { node_ctr += elem_blk_parms[j].num_nodes_per_side[0]; } } ss_elem_node_ndx[i] = node_ctr; /* assign node list index */ free(same_elem_type); /* All setup, ready to go ... */ elem_ctr=0; for (j=0; j < tot_num_ss_elem; j++) { if (side_sets_elem_list[ss_elem_ndx[j]] > elem_ctr) { /* release connectivity array space and get next one */ if (elem_ctr > 0) free(connect); /* Allocate space for the connectivity array for new element block */ if (!(connect= malloc(elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_elem_in_blk* elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_nodes_per_elem* sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate space for connectivity array for file id %d", exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } /* get connectivity array */ if (ex_get_elem_conn( exoid, elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, connect) == -1) { sprintf(errmsg, "Error: failed to get connectivity array for elem blk %d for file id %d", elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } elem_ctr = elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_ctr; } /* For the first node of each side in side set, using a linear search (of up to num_nodes_per_elem) of the connectivity array, locate the node position in the element. The first node position and the second node position are used with a element type specific table to determine the side. */ elem_num = side_sets_elem_list[ss_elem_ndx[j]]-1;/* element number 0-based*/ /* calculate the relative element number position in it's block*/ elem_num_pos = elem_num - (elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_ctr - elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_elem_in_blk); /* calculate the beginning of the node list for this element by using the ss_elem_node_ndx index into the side_sets_node_index and adding the element number position * number of nodes per elem */ num_nodes_per_elem = elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].num_nodes_per_elem; for (n=0; n= 4) /* 4- or 8-node side (front or back face) */ side_sets_side_list[ss_elem_ndx[j]] = shell_table[1][2*n]; else /* 2- or 3-node side (edge of shell) */ side_sets_side_list[ss_elem_ndx[j]] = shell_edge_table[1][2*n]; } else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (shell_table[0][2*n+1]-1)]) { if (num_node_per_side >= 4) /* 4- or 8-node side (front or back face) */ side_sets_side_list[ss_elem_ndx[j]] = shell_table[1][2*n+1]; else /* 2- or 3-node side (edge of shell) */ side_sets_side_list[ss_elem_ndx[j]]=shell_edge_table[1][2*n+1]; } else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (shell_table[0][2*n+2]-1)]) { if (num_node_per_side >= 4) /* 4- or 8-node side (front or back face) */ side_sets_side_list[ss_elem_ndx[j]] = shell_table[1][2*n+2]; else /* 2- or 3-node side (edge of shell) */ side_sets_side_list[ss_elem_ndx[j]]=shell_edge_table[1][2*n+2]; } else { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: failed to find SHELL element %d, node %d in connectivity array %d for file id %d", side_sets_elem_list[ss_elem_ndx[j]], side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1], elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } break; } case HEX: { /* use table to find which node to compare to next */ if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (hex_table[0][3*n]-1)]) side_sets_side_list[ss_elem_ndx[j]] = hex_table[1][3*n]; else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (hex_table[0][3*n+1]-1)]) side_sets_side_list[ss_elem_ndx[j]] = hex_table[1][3*n+1]; else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (hex_table[0][3*n+2]-1)]) side_sets_side_list[ss_elem_ndx[j]] = hex_table[1][3*n+2]; else { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: failed to find HEX element %d, node %d in connectivity array %d for file id %d", side_sets_elem_list[ss_elem_ndx[j]], side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1], elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } break; } case TETRA: { /* use table to find which node to compare to next */ if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (tetra_table[0][3*n]-1)]) side_sets_side_list[ss_elem_ndx[j]] = tetra_table[1][3*n]; else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (tetra_table[0][3*n+1]-1)]) side_sets_side_list[ss_elem_ndx[j]] = tetra_table[1][3*n+1]; else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (tetra_table[0][3*n+2]-1)]) side_sets_side_list[ss_elem_ndx[j]] = tetra_table[1][3*n+2]; else { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: failed to find TETRA element %d, node %d in connectivity array %d for file id %d", side_sets_elem_list[ss_elem_ndx[j]], side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1], elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } break; } case PYRAMID: { /* NOTE: PYRAMID elements in side set node lists are currently not supported */ exerrval = EX_BADPARAM; sprintf(errmsg, "ERROR: unsupported PYRAMID element found in side set node list in file id %d", exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } case WEDGE: { #if 1 /* NOTE: WEDGE elements in side set node lists are currently not supported */ exerrval = EX_BADPARAM; sprintf(errmsg, "ERROR: unsupported WEDGE element found in side set node list in file id %d", exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); #else /* use wedge_table to find which node to compare to next */ /* This section is commented out because Wedges are no longer supported !!!*/ if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (wedge_table[0][3*n]-1)]) side_sets_side_list[ss_elem_ndx[j]] = wedge_table[1][3*n]; else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (wedge_table[0][3*n+1]-1)]) side_sets_side_list[ss_elem_ndx[j]] = wedge_table[1][3*n+1]; else if (side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1] == connect[num_nodes_per_elem*(elem_num_pos)+ (wedge_table[0][3*n+2]-1)]) side_sets_side_list[ss_elem_ndx[j]] = wedge_table[1][3*n+2]; else { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: failed to find WEDGE element %d, node %d in connectivity array %d for file id %d", side_sets_elem_list[ss_elem_ndx[j]], side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]+1], elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } break; #endif } default: { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: %s is an unsupported element type", elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_type); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); return(EX_FATAL); } } break; /* done with this element */ } } if (n >= num_nodes_per_elem) /* did we find the node? */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: failed to find element %d, node %d in element block %d for file id %d", side_sets_elem_list[ss_elem_ndx[j]], side_sets_node_list[ss_elem_node_ndx[ss_elem_ndx[j]]], elem_blk_parms[ss_parm_ndx[ss_elem_ndx[j]]].elem_blk_id, exoid); ex_err("ex_cvt_nodes_to_sides",errmsg,exerrval); free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_FATAL); } } /* All done: release connectivity array space, element block ids array, element block parameters array, and side set element index array */ free(connect); free(ss_elem_node_ndx); free(ss_parm_ndx); free(elem_blk_parms); free(elem_blk_ids); free(ss_elem_ndx); return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exppem.c0000644000175000017500000001736311606020250022262 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exppem - ex_put_partial_elem_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_id element map id * int ent_start first entry in map * int ent_count number of entries in map * int *elem_map element map * * exit conditions - * * revision history - * * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /* for free() */ /*! * writes an element map; this is a vector of integers of length number * of elements */ int ex_put_partial_elem_map (int exoid, int map_id, int ent_start, int ent_count, const int *elem_map) { int status; int dimid, varid, map_ndx, map_exists; size_t start[1]; size_t num_elem_maps, num_elem, count[1]; int cur_num_elem_maps; char *cdum; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ map_exists = 0; cdum = 0; /* Make sure the file contains elements */ if (nc_inq_dimid (exoid, DIM_NUM_ELEM, &dimid) != NC_NOERR ) { return (EX_NOERR); } /* first check if any element maps are specified */ if ((status = nc_inq_dimid(exoid, DIM_NUM_EM, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: no element maps specified in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* Check for duplicate element map id entry */ map_ndx = ex_id_lkup(exoid,EX_ELEM_MAP,map_id); if (exerrval == EX_LOOKUPFAIL) { /* did not find the element map id */ map_exists = 0; /* Map is being defined */ map_ndx = -1; } else { map_exists = 1; /* A portion of this map has already been written */ } if (!map_exists) { /* Get number of element maps initialized for this file */ if ((status = nc_inq_dimlen(exoid,dimid,&num_elem_maps)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of element maps in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* Keep track of the total number of element maps defined using a counter stored in a linked list keyed by exoid. NOTE: ex_get_file_item is used to find the number of element maps for a specific file and returns that value. */ cur_num_elem_maps = ex_get_file_item(exoid, ex_get_counter_list(EX_ELEM_MAP)); if (cur_num_elem_maps >= (int)num_elem_maps) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of element maps (%ld) specified in file id %d", (long)num_elem_maps,exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* NOTE: ex_inc_file_item is used to find the number of element maps for a specific file and returns that value incremented. */ cur_num_elem_maps = ex_inc_file_item(exoid, ex_get_counter_list(EX_ELEM_MAP)); } else { cur_num_elem_maps = map_ndx-1; } /* determine number of elements */ if ((status = nc_inq_dimid(exoid, DIM_NUM_ELEM, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: couldn't determine number of elements in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, &num_elem)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of elements in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* Check input parameters for a valid range of numbers */ if (ent_start <= 0 || (size_t)ent_start > num_elem) { exerrval = EX_FATAL; sprintf(errmsg, "Error: start count is invalid in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } if (ent_count < 0) { exerrval = EX_FATAL; sprintf(errmsg, "Error: Invalid count value in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } if ((size_t)(ent_start+ent_count-1) > num_elem) { exerrval = EX_FATAL; sprintf(errmsg, "Error: start+count-1 is larger than element count in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* write out information to previously defined variable */ /* first get id of variable */ if ((status = nc_inq_varid(exoid, VAR_EM_PROP(1), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate element map ids in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* then, write out element map id */ if (!map_exists) { start[0] = cur_num_elem_maps; if ((status = nc_put_var1_int(exoid, varid, start, &map_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store element map id %d in file id %d", map_id,exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } } /* locate variable array in which to store the element map */ if ((status = nc_inq_varid(exoid,VAR_ELEM_MAP(cur_num_elem_maps+1), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate element map %d in file id %d", map_id,exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } /* write out the element map */ start[0] = ent_start-1; count[0] = ent_count; status = nc_put_vara_int(exoid, varid, start, count, elem_map); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store element map in file id %d", exoid); ex_err("ex_put_partial_elem_map",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgvan.c0000755000175000017500000000547711606020250022262 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgvan - ex_get_var_names * * entry conditions - * input parameters: * int exoid exodus file id * char* var_type variable type: G,N, or E * int num_vars # of variables to read * * exit conditions - * char* var_names ptr array of variable names * * revision history - * * $Id: exgvan.c,v 1.1 2010-01-06 16:33:38 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * reads the names of the results variables from the database * \deprecated Use ex_get_variable_names()(exoid, obj_type, num_vars, var_names) */ int ex_get_var_names (int exoid, const char *var_type, int num_vars, char *var_names[]) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return ex_get_variable_names(exoid, obj_type, num_vars, var_names); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exppn.c0000755000175000017500000001611311606020250022111 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exppn - ex_put_prop_names: write property arrays names * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type type of object (element block, node * set or side set) * int num_props number of properties to be assigned * char** prop_names array of num_props names * * exit conditions - * * revision history - * * $Id: exppn.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the parameters to set up property name arrays * \param exoid exodus file id * \param obj_type type of object * \param num_props number of properties to be assigned * \param **prop_names array of num_props names */ int ex_put_prop_names (int exoid, ex_entity_type obj_type, int num_props, char **prop_names) { int status; int oldfill, temp; int i, propid, dimid, dims[1]; char name[MAX_VAR_NAME_LENGTH+1]; int vals[1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire id of previously defined dimension (number of objects) */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(obj_type), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of %s in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_put_prop_names",errmsg, exerrval); return(EX_FATAL); } nc_set_fill(exoid, NC_FILL, &oldfill); /* fill with zeros per routine spec */ /* put netcdf file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_prop_names",errmsg,exerrval); return (EX_FATAL); } /* define num_props variables; we postpend the netcdf variable name with */ /* a counter starting at 2 because "xx_prop1" is reserved for the id array*/ dims[0] = dimid; for (i=0; i #include "exodusII.h" #include "exodusII_int.h" /*! * writes the EXODUS II variable truth table to the database; also, * creates netCDF variables in which to store EXODUS II variable * values; although this table isn't required (because the netCDF * variables can also be created in ex_put_var), this call will save * tremendous time because all of the variables are defined at once * while the file is in define mode, rather than going in and out of * define mode (causing the entire file to be copied over and over) * which is what occurs when the variables are defined in ex_put_var * \param exoid exodus file id * \param *var_type 'e', 'm', 's' element, nodeset, sideset * \param num_blk number of blocks * \param num_var number of variables * \param *var_tab variable truth table array * \deprecated Use ex_put_truth_table()(exoid, obj_type, num_blk, num_var, var_tab) */ int ex_put_var_tab (int exoid, const char *var_type, int num_blk, int num_var, int *var_tab) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return ex_put_truth_table(exoid, obj_type, num_blk, num_var, var_tab); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvp.c0000755000175000017500000000566411606020250022132 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvp - ex_put_var_param * * entry conditions - * input parameters: * int exoid exodus file id * char* var_type variable type G,N, or E * int* num_vars number of variables in database * * exit conditions - * * revision history - * * $Id: expvp.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the number and names of global, nodal, or element variables * that will be written to the database * \param exoid exodus file id * \param var_type variable type G,N, or E * \param num_vars number of variables in database * \deprecated Use ex_put_variable_param()(exoid, obj_type, num_vars) */ int ex_put_var_param (int exoid, const char *var_type, int num_vars) { ex_entity_type obj_type; obj_type = ex_var_type_to_ex_entity_type(*var_type); return (ex_put_variable_param(exoid, obj_type, num_vars)); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expvpc.c0000755000175000017500000000666511606020250022277 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expvp - ex_put_concat_var_param * * entry conditions - * input parameters: * int exoid exodus file id * int num_g global variable count * int num_n nodal variable count * int num_e element variable count * int num_elem_blk number of element blocks * int* elem_var_tab element variable truth table array * * exit conditions - * * revision history - * * $Id: expvpc.c,v 1.1 2010-01-06 16:33:49 kwleiter Exp $ *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the number of global, nodal, and element variables * that will be written to the database * \param exoid int exodus file id * \param num_g int global variable count * \param num_n int nodal variable count * \param num_e int element variable count * \param num_elem_blk int number of element blocks * \param elem_var_tab int* element variable truth table array * \deprecated Use ex_put_all_var_param()(exoid, num_g, num_n, num_e, elem_var_tab, 0, 0, 0, 0) */ int ex_put_concat_var_param (int exoid, int num_g, int num_n, int num_e, int num_elem_blk, int *elem_var_tab) { (void)num_elem_blk; return ex_put_all_var_param(exoid, num_g, num_n, num_e, elem_var_tab, 0, 0, 0, 0); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expmp.c0000755000175000017500000002352111606020250022111 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expmp - ex_put_map_param * * entry conditions - * input parameters: * int exoid exodus file id * int num_node_maps number of node maps * int num_elem_maps number of element maps * * exit conditions - * * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * defines the number of node and element maps. It is more efficient * to define both of these at the same time; however, they can be * defined in separate calls by setting only one of the counts to a * non-zero value. It is an error to redefine the number of node or * element maps. * \param exoid exodus file id * \param num_node_maps number of node maps * \param num_elem_maps number of element maps */ int ex_put_map_param (int exoid, int num_node_maps, int num_elem_maps) { int dim[2], dimid, strdim, varid, status; int i; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* return if these have been defined before */ if ( (num_node_maps > 0 && ((nc_inq_dimid (exoid, DIM_NUM_NM, &dimid)) == NC_NOERR)) || (num_elem_maps > 0 && ((nc_inq_dimid (exoid, DIM_NUM_EM, &dimid)) == NC_NOERR)) ) { exerrval = EX_MSG; sprintf(errmsg, "Error: number of maps already defined for file id %d",exoid); ex_err("ex_put_map_param",errmsg,exerrval); return (EX_FATAL); } if ( (num_node_maps > 0) || (num_elem_maps > 0) ) { /* inquire previously defined dimensions */ if ((status = nc_inq_dimid (exoid, DIM_STR, &strdim)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_map_param",errmsg,exerrval); return (EX_FATAL); } /* put file into define mode */ if ((status = nc_redef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_map_param",errmsg,exerrval); return (EX_FATAL); } /* node maps: */ if (num_node_maps > 0) { if ((status = nc_def_dim(exoid, DIM_NUM_NM, num_node_maps, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of node maps in file id %d",exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* node maps id array: */ dim[0] = dimid; if ((status = nc_def_var(exoid, VAR_NM_PROP(1), NC_INT, 1, dim, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create node maps property array in file id %d", exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store property name as attribute of property array variable */ if ((status=nc_put_att_text(exoid, varid, ATT_PROP_NAME, 3, "ID")) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store node map property name %s in file id %d", "ID",exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* Node map names... */ dim[0] = dimid; dim[1] = strdim; if (nc_def_var(exoid, VAR_NAME_NM, NC_CHAR, 2, dim, &varid) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define node map name array in file id %d",exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* determine number of nodes */ if ((status = nc_inq_dimid (exoid, DIM_NUM_NODES, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: couldn't determine number of nodes in file id %d", exoid); ex_err("ex_put_node_map",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } dim[0] = dimid; /* create variable array in which to store the node maps */ for (i=0; i < num_node_maps; i++) { if ((status = nc_def_var(exoid,VAR_NODE_MAP(i+1),NC_INT,1,dim,&varid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: node map %d already defined in file id %d", i,exoid); ex_err("ex_put_node_map",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to create node map %d in file id %d", i,exoid); ex_err("ex_put_node_map",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } } } /* element maps: */ if (num_elem_maps > 0) { if ((status = nc_def_dim (exoid, DIM_NUM_EM, num_elem_maps,&dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define number of element maps in file id %d", exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* element maps id array: */ dim[0] = dimid; if ((status = nc_def_var(exoid, VAR_EM_PROP(1), NC_INT, 1, dim, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to create element maps property array in file id %d", exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store property name as attribute of property array variable */ if ((status=nc_put_att_text(exoid, varid, ATT_PROP_NAME, 3, "ID")) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store element map property name %s in file id %d", "ID",exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* Element map names... */ dim[0] = dimid; dim[1] = strdim; if ((status = nc_def_var(exoid, VAR_NAME_EM, NC_CHAR, 2, dim, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to define element map name array in file id %d",exoid); ex_err("ex_put_map_param",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* determine number of elements */ if ((status = nc_inq_dimid(exoid, DIM_NUM_ELEM, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: couldn't determine number of elements in file id %d", exoid); ex_err("ex_put_elem_map",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* create variable array in which to store the element maps */ dim[0] = dimid; for (i = 0; i < num_elem_maps; i++) { if ((status = nc_def_var(exoid,VAR_ELEM_MAP(i+1),NC_INT,1,dim, &varid)) != NC_NOERR) { if (status == NC_ENAMEINUSE) { exerrval = status; sprintf(errmsg, "Error: element map %d already defined in file id %d", i,exoid); ex_err("ex_put_elem_map",errmsg,exerrval); } else { exerrval = status; sprintf(errmsg, "Error: failed to create element map %d in file id %d", i,exoid); ex_err("ex_put_elem_map",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } } } /* leave define mode */ if ((status = nc_enddef (exoid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to complete variable definitions in file id %d",exoid); ex_err("ex_put_map_param",errmsg,exerrval); return (EX_FATAL); } } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (nc_enddef (exoid) != NC_NOERR) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_map_param",errmsg,exerrval); } return (EX_FATAL); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expsstt.c0000644000175000017500000000703511606020250022471 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expsstt - ex_put_sset_var_tab * * entry conditions - * input parameters: * int exoid exodus file id * int num_sset number of sidesets * int num_sset_var number of sideset variables * int* sset_var_tab sideset variable truth table array * * exit conditions - * * $Id: expsstt.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /*! * writes the EXODUS II sideset variable truth table to the database; * also, creates netCDF variables in which to store EXODUS II sideset * variable values; although this table isn't required (because the * netCDF variables can also be created in ex_put_sset_var), this call * will save tremendous time because all of the variables are defined * at once while the file is in define mode, rather than going in and out * of define mode (causing the entire file to be copied over and over) * which is what occurs when the sideset variable values variables are * defined in ex_put_sset_var * \param exoid exodus file id * \param num_sset number of sidesets * \param num_sset_var number of sideset variables * \param *sset_var_tab sideset variable truth table array * \deprecated Use ex_put_truth_table()(exoid, EX_SIDE_SET, num_sset, num_sset_var, sset_var_tab) */ int ex_put_sset_var_tab (int exoid, int num_sset, int num_sset_var, int *sset_var_tab) { return ex_put_truth_table(exoid, EX_SIDE_SET, num_sset, num_sset_var, sset_var_tab); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnvv.c0000755000175000017500000001007211606020250022303 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnv - ex_put_nodal_varid_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step whole time step number * int nodeal_var_index index of desired nodal variable * int num_nodes number of nodal points * int varid id of variable on exodus database * float* nodal_var_vals array of nodal variable values * * exit conditions - * * revision history - * * $Id: expnvv.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of a single nodal variable for a single time step to * the database; assume the first time step and nodal variable index * is 1 * \param exoid exodus file id * \param time_step whole time step number * \param nodal_var_index index of desired nodal variable * \param num_nodes number of nodal points * \param varid id of variable on exodus database * \param nodal_var_vals array of nodal variable values */ int ex_put_nodal_varid_var(int exoid, int time_step, int nodal_var_index, int num_nodes, int varid, const void *nodal_var_vals) { int status; size_t start[3], count[3]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ if (ex_large_model(exoid) == 0) { start[0] = --time_step; start[1] = --nodal_var_index; start[2] = 0; count[0] = 1; count[1] = 1; count[2] = num_nodes; } else { start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_nodes; } if (ex_comp_ws(exoid) == 4) { status = nc_put_vara_float(exoid, varid, start, count, nodal_var_vals); } else { status = nc_put_vara_double(exoid, varid, start, count, nodal_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store nodal variables in file id %d", exoid); ex_err("ex_put_nodal_varid_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/excopy.c0000755000175000017500000006662611606020250022304 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * excopy - ex_copy * * entry conditions - * input parameters: * int in_exoid input exodus file id * * exit conditions - * int out_exoid output exodus file id * * revision history - * * *****************************************************************************/ #include #include #include #include "exodusII.h" #include "exodusII_int.h" struct ncdim { /* dimension */ char name[MAX_STR_LENGTH]; size_t size; }; struct ncvar { /* variable */ char name[MAX_STR_LENGTH]; nc_type type; int ndims; int dims[NC_MAX_VAR_DIMS]; int natts; }; struct ncatt { /* attribute */ int var; char name[MAX_STR_LENGTH]; nc_type type; size_t len; void *val; }; static size_t type_size(nc_type type); static int cpy_att (int, int, int, int); static int cpy_var_def(int, int, int, char*); static int cpy_var_val(int, int, char*); static int cpy_coord_def(int in_id,int out_id,int rec_dim_id, char *var_nm, int in_large, int out_large); static int cpy_coord_val(int in_id,int out_id,char *var_nm, int in_large, int out_large); static void update_internal_structs( int, ex_inquiry, struct list_item** ); /*! * efficiently copies all non-transient information (attributes, * dimensions, and variables from an opened EXODUS file to another * opened EXODUS file. Will not overwrite a dimension or variable * already defined in the new file. * \param in_exoid exodus file id for input file * \param out_exoid exodus file id for output file */ int ex_copy (int in_exoid, int out_exoid) { int status; int ndims; /* number of dimensions */ int nvars; /* number of variables */ int ngatts; /* number of global attributes */ int recdimid; /* id of unlimited dimension */ int dimid; /* dimension id */ int dim_out_id; /* dimension id */ int varid; /* variable id */ int var_out_id; /* variable id */ struct ncvar var; /* variable */ struct ncatt att; /* attribute */ int i; size_t numrec; size_t dim_sz; char dim_nm[NC_MAX_NAME]; int in_large, out_large; exerrval = 0; /* clear error code */ /* * Get exodus_large_model setting on both input and output * databases so know how to handle coordinates. */ in_large = ex_large_model(in_exoid); out_large = ex_large_model(out_exoid); /* * get number of dimensions, number of variables, number of global * atts, and dimension id of unlimited dimension, if any */ nc_inq(in_exoid, &ndims, &nvars, &ngatts, &recdimid); nc_inq_dimlen(in_exoid, recdimid, &numrec); /* put output file into define mode */ nc_redef(out_exoid); /* copy global attributes */ for (i = 0; i < ngatts; i++) { nc_inq_attname(in_exoid, NC_GLOBAL, i, att.name); /* if attribute exists in output file, don't overwrite it; compute * word size, I/O word size etc. are global attributes stored when * file is created with ex_create; we don't want to overwrite those */ if ((status = nc_inq_att(out_exoid, NC_GLOBAL, att.name, &att.type, &att.len)) != NC_NOERR) { /* The "last_written_time" attribute is a special attribute used by the Sierra IO system to determine whether a timestep has been fully written to the database in order to try to detect a database crash that happens in the middle of a database output step. Don't want to copy that attribute. */ if (strcmp(att.name,"last_written_time") != 0) { /* attribute doesn't exist in new file so OK to create it */ nc_copy_att(in_exoid,NC_GLOBAL,att.name,out_exoid,NC_GLOBAL); } } } /* copy dimensions */ /* Get the dimension sizes and names */ for(dimid = 0; dimid < ndims; dimid++){ nc_inq_dim(in_exoid,dimid,dim_nm,&dim_sz); /* If the dimension isn't one we specifically don't want * to copy (ie, number of QA or INFO records) and it * hasn't been defined, copy it */ if ( ( strcmp(dim_nm,DIM_NUM_QA) != 0) && ( strcmp(dim_nm,DIM_NUM_INFO) != 0) && ( strcmp(dim_nm,DIM_NUM_NOD_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_EDG_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_FAC_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_ELE_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_NSET_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_ESET_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_FSET_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_SSET_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_ELSET_VAR) != 0) && ( strcmp(dim_nm,DIM_NUM_GLO_VAR) != 0) ) { /* See if the dimension has already been defined */ status = nc_inq_dimid(out_exoid, dim_nm, &dim_out_id); if(status != NC_NOERR) { if(dimid != recdimid) { status = nc_def_dim(out_exoid, dim_nm, dim_sz, &dim_out_id); } else { status = nc_def_dim(out_exoid, dim_nm, NC_UNLIMITED, &dim_out_id); } /* end else */ } /* end if */ } /* end if */ } /* end loop over dim */ /* copy variable definitions and variable attributes */ for (varid = 0; varid < nvars; varid++) { nc_inq_var(in_exoid, varid, var.name, &var.type, &var.ndims, var.dims, &var.natts); /* we don't want to copy some variables because there is not a * simple way to add to them; * QA records, info records and all results variables (nodal * element, and global results) are examples */ if ( ( strcmp(var.name,VAR_QA_TITLE) != 0) && ( strcmp(var.name,VAR_INFO) != 0) && ( strcmp(var.name,VAR_EBLK_TAB) != 0) && ( strcmp(var.name,VAR_FBLK_TAB) != 0) && ( strcmp(var.name,VAR_ELEM_TAB) != 0) && ( strcmp(var.name,VAR_ELSET_TAB) != 0) && ( strcmp(var.name,VAR_SSET_TAB) != 0) && ( strcmp(var.name,VAR_FSET_TAB) != 0) && ( strcmp(var.name,VAR_ESET_TAB) != 0) && ( strcmp(var.name,VAR_NSET_TAB) != 0) && ( strcmp(var.name,VAR_NAME_GLO_VAR) != 0) && ( strcmp(var.name,VAR_GLO_VAR) != 0) && ( strcmp(var.name,VAR_NAME_NOD_VAR) != 0) && ( strcmp(var.name,VAR_NOD_VAR) != 0) && ( strcmp(var.name,VAR_NAME_EDG_VAR) != 0) && ( strcmp(var.name,VAR_NAME_FAC_VAR) != 0) && ( strcmp(var.name,VAR_NAME_ELE_VAR) != 0) && ( strcmp(var.name,VAR_NAME_NSET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_ESET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_FSET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_SSET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_ELSET_VAR) != 0)&& ( strncmp(var.name,"vals_elset_var", 14) != 0) && ( strncmp(var.name,"vals_sset_var", 13) != 0) && ( strncmp(var.name,"vals_fset_var", 13) != 0) && ( strncmp(var.name,"vals_eset_var", 13) != 0) && ( strncmp(var.name,"vals_nset_var", 13) != 0) && ( strncmp(var.name,"vals_nod_var", 12) != 0) && ( strncmp(var.name,"vals_edge_var", 13) != 0) && ( strncmp(var.name,"vals_face_var", 13) != 0) && ( strncmp(var.name,"vals_elem_var", 13) != 0) ) { if (strncmp(var.name,VAR_COORD,5) == 0) { var_out_id = cpy_coord_def (in_exoid, out_exoid, recdimid, var.name, in_large, out_large); } else { var_out_id = cpy_var_def (in_exoid, out_exoid, recdimid, var.name); } /* copy the variable's attributes */ (void) cpy_att (in_exoid, out_exoid, varid, var_out_id); } } /* take the output file out of define mode */ nc_enddef (out_exoid); /* output variable data */ for (varid = 0; varid < nvars; varid++) { nc_inq_var(in_exoid, varid, var.name, &var.type, &var.ndims, var.dims, &var.natts); /* we don't want to copy some variable values; * QA records and info records shouldn't be copied because there * isn't an easy way to add to them; * the time value array ("time_whole") and any results variables * (nodal, elemental, or global) shouldn't be copied */ if ( ( strcmp(var.name,VAR_QA_TITLE) != 0) && ( strcmp(var.name,VAR_INFO) != 0) && ( strcmp(var.name,VAR_EBLK_TAB) != 0) && ( strcmp(var.name,VAR_FBLK_TAB) != 0) && ( strcmp(var.name,VAR_ELEM_TAB) != 0) && ( strcmp(var.name,VAR_ELSET_TAB) != 0) && ( strcmp(var.name,VAR_SSET_TAB) != 0) && ( strcmp(var.name,VAR_FSET_TAB) != 0) && ( strcmp(var.name,VAR_ESET_TAB) != 0) && ( strcmp(var.name,VAR_NSET_TAB) != 0) && ( strcmp(var.name,VAR_NAME_GLO_VAR) != 0) && ( strcmp(var.name,VAR_GLO_VAR) != 0) && ( strcmp(var.name,VAR_NAME_NOD_VAR) != 0) && ( strcmp(var.name,VAR_NOD_VAR) != 0) && ( strcmp(var.name,VAR_NAME_EDG_VAR) != 0) && ( strcmp(var.name,VAR_NAME_FAC_VAR) != 0) && ( strcmp(var.name,VAR_NAME_ELE_VAR) != 0) && ( strcmp(var.name,VAR_NAME_NSET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_ESET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_FSET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_SSET_VAR) != 0) && ( strcmp(var.name,VAR_NAME_ELSET_VAR) != 0) && ( strncmp(var.name,"vals_elset_var", 14) != 0)&& ( strncmp(var.name,"vals_sset_var", 13) != 0)&& ( strncmp(var.name,"vals_fset_var", 13) != 0)&& ( strncmp(var.name,"vals_eset_var", 13) != 0)&& ( strncmp(var.name,"vals_nset_var", 13) != 0)&& ( strncmp(var.name,"vals_nod_var", 12) != 0) && ( strncmp(var.name,"vals_edge_var",13) != 0) && ( strncmp(var.name,"vals_face_var",13) != 0) && ( strncmp(var.name,"vals_elem_var",13) != 0) && ( strcmp(var.name,VAR_WHOLE_TIME) != 0) ) { if (strncmp(var.name,VAR_COORD,5) == 0) { (void) cpy_coord_val (in_exoid, out_exoid, var.name, in_large, out_large); } else { (void) cpy_var_val (in_exoid, out_exoid, var.name); } } } /* ensure internal data structures are updated */ /* if number of blocks > 0 */ update_internal_structs( out_exoid, EX_INQ_EDGE_BLK, ex_get_counter_list(EX_EDGE_BLOCK)); update_internal_structs( out_exoid, EX_INQ_FACE_BLK, ex_get_counter_list(EX_FACE_BLOCK)); update_internal_structs( out_exoid, EX_INQ_ELEM_BLK, ex_get_counter_list(EX_ELEM_BLOCK)); /* if number of sets > 0 */ update_internal_structs( out_exoid, EX_INQ_NODE_SETS, ex_get_counter_list(EX_NODE_SET)); update_internal_structs( out_exoid, EX_INQ_EDGE_SETS, ex_get_counter_list(EX_EDGE_SET)); update_internal_structs( out_exoid, EX_INQ_FACE_SETS, ex_get_counter_list(EX_FACE_SET)); update_internal_structs( out_exoid, EX_INQ_SIDE_SETS, ex_get_counter_list(EX_SIDE_SET)); update_internal_structs( out_exoid, EX_INQ_ELEM_SETS, ex_get_counter_list(EX_ELEM_SET)); /* if number of maps > 0 */ update_internal_structs( out_exoid, EX_INQ_NODE_MAP, ex_get_counter_list(EX_NODE_MAP)); update_internal_structs( out_exoid, EX_INQ_EDGE_MAP, ex_get_counter_list(EX_EDGE_MAP)); update_internal_structs( out_exoid, EX_INQ_FACE_MAP, ex_get_counter_list(EX_FACE_MAP)); update_internal_structs( out_exoid, EX_INQ_ELEM_MAP, ex_get_counter_list(EX_ELEM_MAP)); return(EX_NOERR); } int cpy_att(int in_id,int out_id,int var_in_id,int var_out_id) /* int in_id: input netCDF input-file ID int out_id: input netCDF output-file ID int var_in_id: input netCDF input-variable ID int var_out_id: input netCDF output-variable ID */ { /* Routine to copy all the attributes from the input netCDF file to the output netCDF file. If var_in_id == NC_GLOBAL, then the global attributes are copied. Otherwise the variable's attributes are copied. */ int idx; int nbr_att; if(var_in_id == NC_GLOBAL) { nc_inq_natts(in_id,&nbr_att); } else { nc_inq_varnatts(in_id, var_in_id, &nbr_att); } /* Get the attributes names, types, lengths, and values */ for (idx=0; idx 0) { for (i=0; i #include "exodusII.h" #include "exodusII_int.h" /*! * reads the EXODUS II variable varids from the database * \deprecated Use ex_get_varid()(exoid, EX_NODE_SET, varid) */ int ex_get_nset_varid (int exoid, int *varid) { return ex_get_varid(exoid, EX_NODE_SET, varid); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exerr.c0000755000175000017500000001163611606020250022111 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exerr - ex_err * * entry conditions - * input parameters: * char* pname procedure name * char* err_string error message string * int errcode error code * * exit conditions - * * revision history - * * $Id: exerr.c,v 1.1 2010-01-06 16:33:05 kwleiter Exp $ * *****************************************************************************/ #include #include #include #include "netcdf.h" #include "exodusII.h" #include "exodusII_int.h" int exerrval = 0; /* clear initial global error code value */ static char last_pname[MAX_ERR_LENGTH]; static char last_errmsg[MAX_ERR_LENGTH]; static int last_errcode; /** * Generalized error reporting function. * global integer used for * suppressing error messages and determining the fatality of errors. * \param pname string containing the name of the calling function. * \param err_string string containing a message explaining the error or problem. * If EX_VERBOSE (see ex_opts()) is true, this message will be * printed to stderr. Otherwise, nothing will be printed. * Maximum length is #MAX_ERR_LENGTH. * \param errcode code identifying the error. EXODUS II C functions * place an error code value in exerrval, an external int. Negative * values are considered fatal errors while positive values are * warnings. There is a set of predefined values defined in * exodusII.h, see group \ref ErrorReturnCodes. * The predefined constant #EX_PRTLASTMSG will cause the * last error message to be output, regardless of the setting of the * error reporting level (see ex_opts()). */ void ex_err(const char *pname, const char *err_string, int errcode) { if (errcode == 0) /* zero is no error, ignore and return */ return; else if (errcode == EX_PRTLASTMSG) { fprintf(stderr, "[%s] %s\n",last_pname,last_errmsg); fprintf(stderr, " exerrval = %d\n",last_errcode); return; } else if (exoptval & EX_VERBOSE) /* check see if we really want to hear this */ { fprintf(stderr, "[%s] %s\n",pname,err_string); if (exoptval & EX_VERBOSE) fprintf(stderr, " exerrval = %d\n",errcode); switch (errcode) { case NC_ESTS: fprintf (stderr," In FORTRAN interface, string too small\n"); break; case NC_EMAXNAME: fprintf (stderr," length of name exceeds NC_MAX_NAME\n"); break; case EX_MSG: break; } } /* save the error message for replays */ strcpy(last_errmsg, err_string); strcpy(last_pname, pname); last_errcode = errcode; fflush(stderr); /* with netCDF 3.4, (fatal) system error codes are > 0; so all EXODUS fatal error codes are > 0 */ if ((errcode > 0) && (exoptval & EX_ABORT)) exit (errcode); } void ex_get_err( const char** msg, const char** func, int* errcode ) { (*msg) = last_errmsg; (*func) = last_pname; (*errcode) = last_errcode; } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgidm.c0000644000175000017500000001015511606020250022231 0ustar amckinstryamckinstry/* * Copyright (c) 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgnm - ex_get_id_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_type type of map (node, edge, face, element) * * exit conditions - * int* map map * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the id map */ int ex_get_id_map ( int exoid, ex_entity_type map_type, int* map ) { size_t i; int dimid, mapid, status; size_t num_entries; char errmsg[MAX_ERR_LENGTH]; const char* dnumentries; const char* vmap; const char* tname; switch (map_type) { case EX_NODE_MAP: tname = "node"; dnumentries = DIM_NUM_NODES; vmap = VAR_NODE_NUM_MAP; break; case EX_EDGE_MAP: tname = "edge"; dnumentries = DIM_NUM_EDGE; vmap = VAR_EDGE_NUM_MAP; break; case EX_FACE_MAP: tname = "face"; dnumentries = DIM_NUM_FACE; vmap = VAR_FACE_NUM_MAP; break; case EX_ELEM_MAP: tname = "element"; dnumentries = DIM_NUM_ELEM; vmap = VAR_ELEM_NUM_MAP; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Bad map type (%d) specified for file id %d", map_type, exoid ); ex_err( "ex_get_id_map", errmsg, exerrval ); return (EX_FATAL); } exerrval = 0; /* clear error code */ /* See if any entries are stored in this file */ if (nc_inq_dimid(exoid, dnumentries,&dimid) != NC_NOERR) { return (EX_NOERR); } if (nc_inq_varid (exoid, vmap, &mapid) != NC_NOERR) { if ((status = nc_inq_dimlen(exoid, dimid, &num_entries)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of %ss in file id %d", tname, exoid); ex_err("ex_get_id_map",errmsg,exerrval); return (EX_FATAL); } /* generate default map of 1..n, where n is num_entries */ for (i=0; i #include "exodusII.h" #include "exodusII_int.h" /*! * writes the side set ID's, side set element count array, * side set element pointers array, side set element list, * side set side list, and distribution factors list. * \param exoid exodus file id * \param side_set_ids array of side set ids * \param num_elem_per_set number of elements/sides/faces per set * \param num_dist_per_set number of distribution factors per set * \param side_sets_elem_index index array of elements into elem list * \param side_sets_dist_index index array of df into df list * \param side_sets_elem_list array of elements * \param side_sets_side_list array of sides/faces * \param side_sets_dist_fact array of distribution factors * \deprecated Use ex_put_concat_sets()(exoid, EX_SIDE_SET, set_specs) */ int ex_put_concat_side_sets (int exoid, int *side_set_ids, int *num_elem_per_set, int *num_dist_per_set, int *side_sets_elem_index, int *side_sets_dist_index, int *side_sets_elem_list, int *side_sets_side_list, void *side_sets_dist_fact) { struct ex_set_specs set_specs; set_specs.sets_ids = side_set_ids; set_specs.num_entries_per_set = num_elem_per_set; set_specs.num_dist_per_set = num_dist_per_set; set_specs.sets_entry_index = side_sets_elem_index; set_specs.sets_dist_index = side_sets_dist_index; set_specs.sets_entry_list = side_sets_elem_list; set_specs.sets_extra_list = side_sets_side_list; set_specs.sets_dist_fact = side_sets_dist_fact; return ex_put_concat_sets(exoid, EX_SIDE_SET, &set_specs); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expssd.c0000755000175000017500000000556111606020250022272 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expssd - ex_put_side_set_dist_fact * * entry conditions - * input parameters: * int exoid exodus file id * int side_set_id side set id * void* side_set_dist_fact array of dist factors for side set * exit conditions - * * revision history - * * $Id: expssd.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the distribution factors for a single side set * \param exoid exodus file id * \param side_set_id side set id * \param *side_set_dist_fact array of dist factors for side set * \deprecated Use ex_put_set_dist_fact()(exoid, EX_SIDE_SET, side_set_id, side_set_dist_fact) */ int ex_put_side_set_dist_fact (int exoid, int side_set_id, const void *side_set_dist_fact) { return ex_put_set_dist_fact(exoid, EX_SIDE_SET, side_set_id, side_set_dist_fact); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exginix.c0000644000175000017500000001344711606020250022436 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgini - ex_get_init * * entry conditions - * input parameters: * int exoid exodus file id * * exit conditions - * ex_init_params* info parameter information * * revision history - * * $Id: exginix.c,v 1.1 2010-01-06 16:33:12 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* Used to reduce repeated code below */ #define EX_GET_DIM_VALUE(TNAME,DNAME,DIMVAR,SDIMVAL) \ if ((status = nc_inq_dimid (exoid, DNAME, &DIMVAR)) != NC_NOERR) { \ /* TNAME are optional and default to zero. */ \ SDIMVAL = 0; \ } else { \ if ((status = nc_inq_dimlen(exoid, DIMVAR, &lnum)) != NC_NOERR) { \ exerrval = status; \ sprintf(errmsg, "Error: failed to get number of " TNAME " in file id %d", \ exoid); \ ex_err("ex_get_init",errmsg,exerrval); \ return (EX_FATAL); \ } \ SDIMVAL = lnum; \ } /*! * reads the initialization parameters from an opened EXODUS II file * \param exoid exodus file id * \param[out] info #ex_init_params structure containing metadata for mesh. * \sa ex_get_init() */ int ex_get_init_ext (int exoid, ex_init_params *info) { int dimid; size_t lnum; char errmsg[MAX_ERR_LENGTH]; int status; size_t title_len; nc_type title_type; exerrval = 0; /* clear error code */ if ((status = nc_inq_att(exoid, NC_GLOBAL, ATT_TITLE, &title_type, &title_len)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to inquire title in file id %d", exoid); ex_err("ex_get_init",errmsg,exerrval); return (EX_FATAL); } /* Check title length to avoid overrunning clients memory space; include trailing null */ if (title_len > MAX_LINE_LENGTH+1) { sprintf(errmsg, "Error: Title is too long (%d characters) in file id %d", (int)title_len-1, exoid); exerrval = -1; ex_err("ex_get_init",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_get_att_text(exoid, NC_GLOBAL, ATT_TITLE, info->title)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get title in file id %d", exoid); ex_err("ex_get_init",errmsg,exerrval); return (EX_FATAL); } info->title[title_len] = '\0'; status = ex_get_dimension(exoid, DIM_NUM_DIM, "dimensions", &lnum, &dimid, "ex_get_init"); if (status != NC_NOERR) return status; info->num_dim = lnum; /* Handle case with zero-nodes */ EX_GET_DIM_VALUE( "nodes",DIM_NUM_NODES,dimid,info->num_nodes); EX_GET_DIM_VALUE( "edges", DIM_NUM_EDGE,dimid,info->num_edge); EX_GET_DIM_VALUE( "faces", DIM_NUM_FACE,dimid,info->num_face); EX_GET_DIM_VALUE("elements", DIM_NUM_ELEM,dimid,info->num_elem); EX_GET_DIM_VALUE("element blocks", DIM_NUM_EL_BLK,dimid,info->num_elem_blk); if (info->num_elem_blk == 0 && info->num_elem > 0) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of element blocks in file id %d", exoid); ex_err("ex_get_init",errmsg,exerrval); return (EX_FATAL); } EX_GET_DIM_VALUE("node sets", DIM_NUM_NS,dimid,info->num_node_sets); EX_GET_DIM_VALUE("edge sets", DIM_NUM_ES,dimid,info->num_edge_sets); EX_GET_DIM_VALUE("face sets", DIM_NUM_FS,dimid,info->num_face_sets); EX_GET_DIM_VALUE("side sets", DIM_NUM_SS,dimid,info->num_side_sets); EX_GET_DIM_VALUE("elem sets",DIM_NUM_ELS,dimid,info->num_elem_sets); EX_GET_DIM_VALUE("node maps", DIM_NUM_NM,dimid,info->num_node_maps); EX_GET_DIM_VALUE("edge maps",DIM_NUM_EDM,dimid,info->num_edge_maps); EX_GET_DIM_VALUE("face maps",DIM_NUM_FAM,dimid,info->num_face_maps); EX_GET_DIM_VALUE("elem maps", DIM_NUM_EM,dimid,info->num_elem_maps); /* Edge and face blocks are also optional (for backwards compatability) */ EX_GET_DIM_VALUE("edge blocks",DIM_NUM_ED_BLK,dimid,info->num_edge_blk); EX_GET_DIM_VALUE("face blocks",DIM_NUM_FA_BLK,dimid,info->num_face_blk); return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnv.c0000755000175000017500000001123511606020250022117 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnv - ex_put_nodal_var * * entry conditions - * input parameters: * int exoid exodus file id * int time_step whole time step number * int nodeal_var_index index of desired nodal variable * int num_nodes number of nodal points * float* nodal_var_vals array of nodal variable values * * exit conditions - * * revision history - * * $Id: expnv.c,v 1.1 2010-01-06 16:33:43 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the values of a single nodal variable for a single time step to * the database; assume the first time step and nodal variable index * is 1 * \param exoid exodus file id * \param time_step whole time step number * \param nodal_var_index index of desired nodal variable * \param num_nodes number of nodal points * \param nodal_var_vals array of nodal variable values */ int ex_put_nodal_var (int exoid, int time_step, int nodal_var_index, int num_nodes, const void *nodal_var_vals) { int status; int varid; size_t start[3], count[3]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ if (ex_large_model(exoid) == 0) { /* write values of the nodal variable */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variables in file id %d", exoid); ex_err("ex_put_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --time_step; start[1] = --nodal_var_index; start[2] = 0; count[0] = 1; count[1] = 1; count[2] = num_nodes; } else { /* nodal variables stored separately, find variable for this variable index */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(nodal_var_index), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", nodal_var_index, exoid); ex_err("ex_put_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_nodes; } if (ex_comp_ws(exoid) == 4) { status = nc_put_vara_float(exoid, varid, start, count, nodal_var_vals); } else { status = nc_put_vara_double(exoid, varid, start, count, nodal_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store nodal variables in file id %d", exoid); ex_err("ex_put_nodal_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnsd.c0000755000175000017500000000560611606020250022265 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnsd - ex_put_node_set_dist_fact * * entry conditions - * input parameters: * int exoid exodus file id * int node_set_id node set id * void* node_set _dist_fact node distribution factors for node set * * exit conditions - * * revision history - * * $Id: expnsd.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes the node set distribution factors for a single node set * \param exoid exodus file id * \param node_set_id node set id * \param node_set_dist_fact node distribution factors for node set * \deprecated Use ex_put_set_dist_fact()(exoid, EX_NODE_SET, node_set_id, node_set_dist_fact) */ int ex_put_node_set_dist_fact (int exoid, int node_set_id, const void *node_set_dist_fact) { return ex_put_set_dist_fact(exoid, EX_NODE_SET, node_set_id, node_set_dist_fact); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgids.c0000644000175000017500000001020111606020250022227 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * $Id: exgids.c,v 1.1 2010-01-06 16:33:12 kwleiter Exp $ * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* * reads the element block ids from the database */ int ex_get_ids (int exoid, ex_entity_type obj_type, int *ids) { int varid, status; char errmsg[MAX_ERR_LENGTH]; const char* varidobj; exerrval = 0; /* clear error code */ switch (obj_type) { case EX_EDGE_BLOCK: varidobj = VAR_ID_ED_BLK; break; case EX_FACE_BLOCK: varidobj = VAR_ID_FA_BLK; break; case EX_ELEM_BLOCK: varidobj = VAR_ID_EL_BLK; break; case EX_NODE_SET: varidobj = VAR_NS_IDS; break; case EX_EDGE_SET: varidobj = VAR_ES_IDS; break; case EX_FACE_SET: varidobj = VAR_FS_IDS; break; case EX_SIDE_SET: varidobj = VAR_SS_IDS; break; case EX_ELEM_SET: varidobj = VAR_ELS_IDS; break; case EX_NODE_MAP: varidobj = VAR_NM_PROP(1); break; case EX_EDGE_MAP: varidobj = VAR_EDM_PROP(1); break; case EX_FACE_MAP: varidobj = VAR_FAM_PROP(1); break; case EX_ELEM_MAP: varidobj = VAR_EM_PROP(1); break; default:/* invalid variable type */ exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid type specified in file id %d", exoid); ex_err("ex_get_ids",errmsg,exerrval); return(EX_FATAL); } /* Determine if there are any 'obj-type' objects */ if ((status = nc_inq_dimid (exoid, ex_dim_num_objects(obj_type), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no %s defined in file id %d", ex_name_of_object(obj_type), exoid); ex_err("ex_get_ids",errmsg,exerrval); return (EX_WARN); } /* inquire id's of previously defined dimensions and variables */ if ((status = nc_inq_varid(exoid, varidobj, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s ids variable in file id %d", ex_name_of_object(obj_type),exoid); ex_err("ex_get_ids",errmsg,exerrval); return (EX_FATAL); } /* read in the element block ids */ status = nc_get_var_int(exoid, varid, ids); if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to return %s ids in file id %d", ex_name_of_object(obj_type),exoid); ex_err("ex_get_ids",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgoatt.c0000644000175000017500000001551111606020250022430 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgeat - ex_get_one_attr * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type object type (edge, face, elem block) * int obj_id object id (edge face, elem block ID) * * exit conditions - * float* attrib array of attributes * * revision history - * * $Id: exgoatt.c,v 1.1 2010-01-06 16:33:30 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /* * reads the attributes for an edge, face, or element block */ int ex_get_one_attr( int exoid, ex_entity_type obj_type, int obj_id, int attrib_index, void* attrib ) { int status; int attrid, obj_id_ndx = 0; int temp; size_t num_entries_this_obj, num_attr; size_t start[2], count[2]; ptrdiff_t stride[2]; char errmsg[MAX_ERR_LENGTH]; const char* dnumobjent; const char* dnumobjatt; const char* vattrbname; exerrval = 0; /* clear error code */ /* Determine index of obj_id in vobjids array */ if (obj_type != EX_NODAL) { obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes found for NULL %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_one_attr",errmsg,EX_MSG); return (EX_WARN); /* no attributes for this object */ } else { sprintf(errmsg, "Warning: failed to locate %s id %d in id array in file id %d", ex_name_of_object(obj_type),obj_id, exoid); ex_err("ex_get_one_attr",errmsg,exerrval); return (EX_WARN); } } } switch (obj_type) { case EX_SIDE_SET: dnumobjent = DIM_NUM_SIDE_SS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx); vattrbname = VAR_SSATTRIB(obj_id_ndx); break; case EX_NODE_SET: dnumobjent = DIM_NUM_NOD_NS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx); vattrbname = VAR_NSATTRIB(obj_id_ndx); break; case EX_EDGE_SET: dnumobjent = DIM_NUM_EDGE_ES(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx); vattrbname = VAR_ESATTRIB(obj_id_ndx); break; case EX_FACE_SET: dnumobjent = DIM_NUM_FACE_FS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx); vattrbname = VAR_FSATTRIB(obj_id_ndx); break; case EX_ELEM_SET: dnumobjent = DIM_NUM_ELE_ELS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx); vattrbname = VAR_ELSATTRIB(obj_id_ndx); break; case EX_NODAL: dnumobjent = DIM_NUM_NODES; dnumobjatt = DIM_NUM_ATT_IN_NBLK; vattrbname = VAR_NATTRIB; break; case EX_EDGE_BLOCK: dnumobjent = DIM_NUM_ED_IN_EBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx); vattrbname = VAR_EATTRIB(obj_id_ndx); break; case EX_FACE_BLOCK: dnumobjent = DIM_NUM_FA_IN_FBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx); vattrbname = VAR_FATTRIB(obj_id_ndx); break; case EX_ELEM_BLOCK: dnumobjent = DIM_NUM_EL_IN_BLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx); vattrbname = VAR_ATTRIB(obj_id_ndx); break; default: sprintf(errmsg, "Error: Called with invalid obj_type %d", obj_type); ex_err("ex_get_one_attr",errmsg,exerrval); return (EX_FATAL); } /* inquire id's of previously defined dimensions */ if (ex_get_dimension(exoid, dnumobjent,"entries", &num_entries_this_obj, &temp, "ex_get_one_attr") != NC_NOERR) return EX_FATAL; if (ex_get_dimension(exoid, dnumobjatt,"attributes", &num_attr, &temp, "ex_get_one_attr") != NC_NOERR) return EX_FATAL; if (attrib_index < 1 || attrib_index > (int)num_attr) { exerrval = EX_FATAL; sprintf(errmsg, "Error: Invalid attribute index specified: %d. Valid range is 1 to %d for %s %d in file id %d", attrib_index, (int)num_attr, ex_name_of_object(obj_type), obj_id, exoid); ex_err("ex_get_one_attr",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_varid(exoid, vattrbname, &attrid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate attributes for %s %d in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_one_attr",errmsg,exerrval); return (EX_FATAL); } /* read in the attributes */ start[0] = 0; start[1] = attrib_index-1; count[0] = num_entries_this_obj; count[1] = 1; stride[0] = 1; stride[1] = num_attr; if (ex_comp_ws(exoid) == 4) { status = nc_get_vars_float(exoid, attrid, start, count, stride, attrib); } else { status = nc_get_vars_double(exoid, attrid, start, count, stride, attrib); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get attribute %d for %s %d in file id %d", attrib_index, ex_name_of_object(obj_type), obj_id,exoid); ex_err("ex_get_one_attr",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expem.c0000755000175000017500000000526111606020250022077 0ustar amckinstryamckinstry/* * Copyright (c) 2006 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expem - ex_put_elem_map * * entry conditions - * input parameters: * int exoid exodus file id * int map_id element map id * int *elem_map element map * * exit conditions - * * revision history - * * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" /*! * writes an element map; this is a vector of integers of length number * of elements * \param exoid exodus file id * \param map_id element map id * \param elem_map element map * \deprecated Use ex_put_num_map()(exoid, EX_ELEM_MAP, map_id, elem_map) */ int ex_put_elem_map (int exoid, int map_id, const int *elem_map) { return ex_put_num_map( exoid, EX_ELEM_MAP, map_id, elem_map ); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnam.c0000644000175000017500000001125111606020250022242 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnam - ex_put_name * * environment - UNIX * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type object type * int entity_id id of entity name to write * char* name ptr to entity name * * exit conditions - * * revision history - * * $Id: expnam.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the name of the specified entity to the database. * \param exoid exodus file id * \param obj_type object type * \param entity_id id of entity name to write * \param name ptr to entity name */ int ex_put_name (int exoid, ex_entity_type obj_type, int entity_id, const char *name) { int status; int varid, ent_ndx; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; const char *routine = "ex_put_name"; const char *vobj; exerrval = 0; /* clear error code */ switch(obj_type) { case EX_EDGE_BLOCK: vobj = VAR_NAME_ED_BLK; break; case EX_FACE_BLOCK: vobj = VAR_NAME_FA_BLK; break; case EX_ELEM_BLOCK: vobj = VAR_NAME_EL_BLK; break; case EX_NODE_SET: vobj = VAR_NAME_NS; break; case EX_SIDE_SET: vobj = VAR_NAME_SS; break; case EX_EDGE_SET: vobj = VAR_NAME_ES; break; case EX_FACE_SET: vobj = VAR_NAME_FS; break; case EX_ELEM_SET: vobj = VAR_NAME_ELS; break; case EX_NODE_MAP: vobj = VAR_NAME_NM; break; case EX_EDGE_MAP: vobj = VAR_NAME_EDM; break; case EX_FACE_MAP: vobj = VAR_NAME_FAM; break; case EX_ELEM_MAP: vobj = VAR_NAME_EM; break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid type specified in file id %d", exoid); ex_err(routine,errmsg,exerrval); return(EX_FATAL); } if ((status = nc_inq_varid(exoid, vobj, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s names in file id %d", ex_name_of_object(obj_type), exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } ent_ndx = ex_id_lkup(exoid, obj_type, entity_id); /* If this is a null entity, then 'ent_ndx' will be negative. * We don't care in this routine, so make it positive and continue... */ if (ent_ndx < 0) ent_ndx = -ent_ndx; /* write EXODUS entityname */ start[0] = ent_ndx-1; start[1] = 0; count[0] = 1; count[1] = strlen(name) + 1; if ((status = nc_put_vara_text(exoid, varid, start, count, name)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to store %s name for id %d in file id %d", ex_name_of_object(obj_type), entity_id, exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/exgfrm.c0000755000175000017500000001776511606020250022265 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * exgfrm - ex_get_coordinate_frames: read coordinate frames * * entry conditions - * input parameters: * int exoid exodus file id * * NOTE: * cf_ids, pt_coordinates and tags may all be NULL, otherwise, they * must have sufficient memory to store the output data. Two calls * to this routine are anticipated (one to get nframes, the second * to fill the data. i.e. * ex_get_coordinate_frames(exoid,&nframes,0,0,0); * ... allocate memory ... * ex_get_coordinate_frames(exoid,&nframe,id,coords,tags); * * * output conditions - * int* nframes number of coordinate frames in model * const int* cf_ids coordinate ids * dimension int[nframes] * const void* pt_coordinates pointer to coordinates. 9 values per * coordinate frame * dimension float[9*nframes] * const char* tags character tag for each frame. * 'r' - rectangular * 'c' - cylindrical * 's' - spherical * dimension char[nframes] * * returns - * EX_NOERR for no error * EX_FATAL for fatal errors * *****************************************************************************/ #include #include "exodusII.h" #include "exodusII_int.h" /* -------------------- local defines --------------------------- */ #define PROCNAME "ex_get_coordinate_frames" /* -------------------- end of local defines -------------------- */ /*! * Coordinate frames are stored in the database as a series of three * points (defined in the basic cartesian coordinate system). The * first of these points describes the origin of the new system. The * second point lies on the 3 axis (or Z axis) of the frame. The third * point is in the 1-3 (xz) plane. Each coordinate frame is identified * by a unique, integer coordinate ID, and by a character tag * indicating whether the frame is rectangular cartesian * "R", cylindrical "C, or spherical "S". * Because the coordinates are floating point values, * the application code must declare the arrays passed to be the * appropriate type "float" or "double" to match the * compute word size passed in ex_create() or * ex_open(). * \param exoid exodus file id * \param[in,out] nframes if 'cf_ids' is NULL, then nframes is returned with the number * of defined coordinate frames. Else it is the number of coordinate * frames to read. * \param[out] cf_ids The (nframes) coordinate frame Ids. If cf_ids is * NULL, no data will be returned in this or any other array. Only * nframes will be modified. Otherwise, space must be allocated to * store 'nframes' integers before making this call. * \param[out] pt_coordinates The (9*nframes) coordinates of the three * points defining each coordinate axis. The first three values are * the origin of the first frame. The next three values are the * coordinates of a point on the 3rd axis of the first frame. The next * three values are the coordinates of a point in the plane of the 1-3 * axis. The pattern is repeated for each frame. If 'cf_ids' * is null, no data will be returned in this array. Otherwise, space * must be allocated for 9*nframes floating point values. The size of * the allocation depends upon the compute word size. * \param[out] tags The (nframes) character tags associated with each * coordinate frame. If 'cf_ids' is NULL, no data will be * returned in this array. Otherwise, space must be allocated for * 'nframes' characters. */ int ex_get_coordinate_frames( int exoid, int *nframes, int *cf_ids, void* pt_coordinates, char* tags) { int status; int dimid; /* ID of the dimension of # frames */ char errmsg[MAX_ERR_LENGTH]; int varids; /* variable id for the frame ids */ size_t start=0; /* start value for varputs */ size_t count; /* number vars to put in varput */ /* get the dimensions */ assert( nframes !=NULL ); status = nc_inq_dimid(exoid, NUM_CFRAMES, &dimid); if (status != NC_NOERR){ *nframes=0; return EX_NOERR; } nc_inq_dimlen(exoid,dimid,&count); *nframes=(int)count; if ( count==0 ) return (EX_NOERR); if ( cf_ids ) if ((status = nc_inq_varid(exoid,FRAME_IDS, &varids))!= NC_NOERR || (nc_get_var_int(exoid,varids,cf_ids)!= NC_NOERR)) { exerrval = status; sprintf(errmsg, "Error: failed to read number coordinate ids from file id %d", exoid); ex_err(PROCNAME,errmsg,exerrval); return (EX_FATAL); } if ( tags ) if ( (status = nc_inq_varid(exoid,FRAME_TAGS,&varids))!= NC_NOERR || (nc_get_vara_text(exoid,varids,&start,&count,tags) != NC_NOERR)) { exerrval = status; sprintf(errmsg, "Error: failed to read number coordinate tags from file id %d", exoid); ex_err(PROCNAME,errmsg,exerrval); return (EX_FATAL); } if (pt_coordinates ){ if ( (status = nc_inq_varid(exoid,FRAME_COORDS,&varids))!= NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to read number coordinate tags from file id %d", exoid); ex_err(PROCNAME,errmsg,exerrval); return (EX_FATAL); } if (ex_comp_ws(exoid) == 4) { status = nc_get_var_float(exoid,varids,pt_coordinates); } else { status = nc_get_var_double(exoid,varids,pt_coordinates); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to read number coordinate tags from file id %d", exoid); ex_err(PROCNAME,errmsg,exerrval); return (EX_FATAL); } } return (EX_NOERR); } xdmf-2.1.dfsg.1/Utilities/vtkexodus2/expnams.c0000644000175000017500000001127211606020250022430 0ustar amckinstryamckinstry/* * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement * retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of Sandia Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /***************************************************************************** * * expnam - ex_put_names * * environment - UNIX * * entry conditions - * input parameters: * int exoid exodus file id * int obj_type object type * char* names ptr array of entity names * * exit conditions - * * revision history - * * $Id: expnams.c,v 1.1 2010-01-06 16:33:42 kwleiter Exp $ * *****************************************************************************/ #include "exodusII.h" #include "exodusII_int.h" #include /*! * writes the names of the results variables to the database * \param exoid exodus file id * \param obj_type object type * \param names ptr array of entity names */ int ex_put_names (int exoid, ex_entity_type obj_type, char* names[]) { int status; int varid; size_t i, num_entity; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; const char *vname = NULL; const char *routine = "ex_put_names"; exerrval = 0; /* clear error code */ switch (obj_type) { /* ======== BLOCKS ========= */ case EX_EDGE_BLOCK: vname = VAR_NAME_ED_BLK; break; case EX_FACE_BLOCK: vname = VAR_NAME_FA_BLK; break; case EX_ELEM_BLOCK: vname = VAR_NAME_EL_BLK; break; /* ======== SETS ========= */ case EX_NODE_SET: vname = VAR_NAME_NS; break; case EX_EDGE_SET: vname = VAR_NAME_ES; break; case EX_FACE_SET: vname = VAR_NAME_FS; break; case EX_SIDE_SET: vname = VAR_NAME_SS; break; case EX_ELEM_SET: vname = VAR_NAME_ELS; break; /* ======== MAPS ========= */ case EX_NODE_MAP: vname = VAR_NAME_NM; break; case EX_EDGE_MAP: vname = VAR_NAME_EDM; break; case EX_FACE_MAP: vname = VAR_NAME_FAM; break; case EX_ELEM_MAP: vname = VAR_NAME_EM; break; /* ======== ERROR (Invalid type) ========= */ default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid type specified in file id %d", exoid); ex_err(routine,errmsg,exerrval); return(EX_FATAL); } ex_get_dimension(exoid, ex_dim_num_objects(obj_type), ex_name_of_object(obj_type), &num_entity, &varid, routine); if ((status = nc_inq_varid(exoid, vname, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s names in file id %d", ex_name_of_object(obj_type), exoid); ex_err(routine,errmsg,exerrval); return (EX_FATAL); } /* write EXODUS entitynames */ for (i=0; i #include #include #include #include #ifdef LIBXML_MODULES_ENABLED struct _xmlModule { unsigned char *name; void *handle; }; static void *xmlModulePlatformOpen(const char *name); static int xmlModulePlatformClose(void *handle); static int xmlModulePlatformSymbol(void *handle, const char *name, void **result); /************************************************************************ * * * module memory error handler * * * ************************************************************************/ /** * xmlModuleErrMemory: * @extra: extra information * * Handle an out of memory condition */ static void xmlModuleErrMemory(xmlModulePtr module, const char *extra) { const char *name = NULL; if (module != NULL) { name = (const char *) module->name; } __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_MODULE, XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra, name, NULL, 0, 0, "Memory allocation failed : %s\n", extra); } /** * xmlModuleOpen: * @name: the module name * @options: a set of xmlModuleOption * * Opens a module/shared library given its name or path * TODO: options are not yet implemented. * * Returns a handle for the module or NULL in case of error */ xmlModulePtr xmlModuleOpen(const char *name, int options ATTRIBUTE_UNUSED) { xmlModulePtr module; module = (xmlModulePtr) xmlMalloc(sizeof(xmlModule)); if (module == NULL) { xmlModuleErrMemory(NULL, "creating module"); return (NULL); } memset(module, 0, sizeof(xmlModule)); module->handle = xmlModulePlatformOpen(name); if (module->handle == NULL) { xmlFree(module); __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_MODULE, XML_MODULE_OPEN, XML_ERR_FATAL, NULL, 0, 0, name, NULL, 0, 0, "failed to open %s\n", name); return(NULL); } module->name = xmlStrdup((const xmlChar *) name); return (module); } /** * xmlModuleSymbol: * @module: the module * @name: the name of the symbol * @symbol: the resulting symbol address * * Lookup for a symbol address in the given module * * Returns 0 if the symbol was found, or -1 in case of error */ int xmlModuleSymbol(xmlModulePtr module, const char *name, void **symbol) { int rc = -1; if ((NULL == module) || (symbol == NULL)) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_MODULE, XML_MODULE_OPEN, XML_ERR_FATAL, NULL, 0, 0, NULL, NULL, 0, 0, "null parameter\n"); return rc; } rc = xmlModulePlatformSymbol(module->handle, name, symbol); if (rc == -1) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_MODULE, XML_MODULE_OPEN, XML_ERR_FATAL, NULL, 0, 0, name, NULL, 0, 0, "failed to find symbol: %s\n", (name == NULL ? "NULL" : name)); return rc; } return rc; } /** * xmlModuleClose: * @module: the module handle * * The close operations unload the associated module and free the * data associated to the module. * * Returns 0 in case of success, -1 in case of argument error and -2 * if the module could not be closed/unloaded. */ int xmlModuleClose(xmlModulePtr module) { int rc; if (NULL == module) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_MODULE, XML_MODULE_CLOSE, XML_ERR_FATAL, NULL, 0, 0, NULL, NULL, 0, 0, "null module pointer\n"); return -1; } rc = xmlModulePlatformClose(module->handle); if (rc != 0) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_MODULE, XML_MODULE_CLOSE, XML_ERR_FATAL, NULL, 0, 0, (const char *) module->name, NULL, 0, 0, "failed to close: %s\n", module->name); return -2; } rc = xmlModuleFree(module); return (rc); } /** * xmlModuleFree: * @module: the module handle * * The free operations free the data associated to the module * but does not unload the associated shared library which may still * be in use. * * Returns 0 in case of success, -1 in case of argument error */ int xmlModuleFree(xmlModulePtr module) { if (NULL == module) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_MODULE, XML_MODULE_CLOSE, XML_ERR_FATAL, NULL, 0, NULL, NULL, NULL, 0, 0, "null module pointer\n"); return -1; } xmlFree(module->name); xmlFree(module); return (0); } #ifdef HAVE_DLOPEN #ifdef HAVE_DLFCN_H #include #endif #ifndef RTLD_GLOBAL /* For Tru64 UNIX 4.0 */ #define RTLD_GLOBAL 0 #endif /** * xmlModulePlatformOpen: * @name: path to the module * * returns a handle on success, and zero on error. */ static void * xmlModulePlatformOpen(const char *name) { return dlopen(name, RTLD_GLOBAL | RTLD_NOW); } /* * xmlModulePlatformClose: * @handle: handle to the module * * returns 0 on success, and non-zero on error. */ static int xmlModulePlatformClose(void *handle) { return dlclose(handle); } /* * xmlModulePlatformSymbol: * http://www.opengroup.org/onlinepubs/009695399/functions/dlsym.html * returns 0 on success and the loaded symbol in result, and -1 on error. */ static int xmlModulePlatformSymbol(void *handle, const char *name, void **symbol) { *symbol = dlsym(handle, name); if (dlerror() != NULL) { return -1; } return 0; } #else /* ! HAVE_DLOPEN */ #ifdef HAVE_SHLLOAD /* HAVE_SHLLOAD */ #ifdef HAVE_DL_H #include #endif /* * xmlModulePlatformOpen: * returns a handle on success, and zero on error. */ static void * xmlModulePlatformOpen(const char *name) { return shl_load(name, BIND_IMMEDIATE, 0L); } /* * xmlModulePlatformClose: * returns 0 on success, and non-zero on error. */ static int xmlModulePlatformClose(void *handle) { return shl_unload(handle); } /* * xmlModulePlatformSymbol: * http://docs.hp.com/en/B2355-90683/shl_load.3X.html * returns 0 on success and the loaded symbol in result, and -1 on error. */ static int xmlModulePlatformSymbol(void *handle, const char *name, void **symbol) { int rc; errno = 0; rc = shl_findsym((shl_t*)&handle, name, TYPE_UNDEFINED, symbol); return rc; } #endif /* HAVE_SHLLOAD */ #endif /* ! HAVE_DLOPEN */ #if defined(_WIN32) && !defined(HAVE_DLOPEN) #include /* * xmlModulePlatformOpen: * returns a handle on success, and zero on error. */ static void * xmlModulePlatformOpen(const char *name) { return LoadLibrary(name); } /* * xmlModulePlatformClose: * returns 0 on success, and non-zero on error. */ static int xmlModulePlatformClose(void *handle) { int rc; rc = FreeLibrary(handle); return (0 == rc); } /* * xmlModulePlatformSymbol: * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getprocaddress.asp * returns 0 on success and the loaded symbol in result, and -1 on error. */ static int xmlModulePlatformSymbol(void *handle, const char *name, void **symbol) { *symbol = GetProcAddress(handle, name); return (NULL == *symbol) ? -1 : 0; } #endif /* _WIN32 */ #ifdef HAVE_BEOS #include /* * xmlModulePlatformOpen: * beos api info: http://www.beunited.org/bebook/The%20Kernel%20Kit/Images.html * returns a handle on success, and zero on error. */ static void * xmlModulePlatformOpen(const char *name) { return (void *) load_add_on(name); } /* * xmlModulePlatformClose: * beos api info: http://www.beunited.org/bebook/The%20Kernel%20Kit/Images.html * returns 0 on success, and non-zero on error. */ static int xmlModulePlatformClose(void *handle) { status_t rc; rc = unload_add_on((image_id) handle); if (rc == B_OK) return 0; else return -1; } /* * xmlModulePlatformSymbol: * beos api info: http://www.beunited.org/bebook/The%20Kernel%20Kit/Images.html * returns 0 on success and the loaded symbol in result, and -1 on error. */ static int xmlModulePlatformSymbol(void *handle, const char *name, void **symbol) { status_t rc; rc = get_image_symbol((image_id) handle, name, B_SYMBOL_TYPE_ANY, symbol); return (rc == B_OK) ? 0 : -1; } #endif /* HAVE_BEOS */ #ifdef HAVE_OS2 #include /* * xmlModulePlatformOpen: * os2 api info: http://www.edm2.com/os2api/Dos/DosLoadModule.html * returns a handle on success, and zero on error. */ static void * xmlModulePlatformOpen(const char *name) { char errbuf[256]; void *handle; int rc; rc = DosLoadModule(errbuf, sizeof(errbuf) - 1, name, &handle); if (rc) return 0; else return (handle); } /* * xmlModulePlatformClose: * os2 api info: http://www.edm2.com/os2api/Dos/DosFreeModule.html * returns 0 on success, and non-zero on error. */ static int xmlModulePlatformClose(void *handle) { return DosFreeModule(handle); } /* * xmlModulePlatformSymbol: * os2 api info: http://www.edm2.com/os2api/Dos/DosQueryProcAddr.html * returns 0 on success and the loaded symbol in result, and -1 on error. */ static int xmlModulePlatformSymbol(void *handle, const char *name, void **symbol) { int rc; rc = DosQueryProcAddr(handle, 0, name, symbol); return (rc == NO_ERROR) ? 0 : -1; } #endif /* HAVE_OS2 */ #define bottom_xmlmodule #include "elfgcchack.h" #endif /* LIBXML_MODULES_ENABLED */ xdmf-2.1.dfsg.1/Utilities/vtklibxml2/threads.c0000644000175000017500000005402611606020250022373 0ustar amckinstryamckinstry/** * threads.c: set of generic threading related routines * * See Copyright for the status of this software. * * Gary Pennington * daniel@veillard.com */ #define IN_LIBXML #include "libxml.h" #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_PTHREAD_H #include #endif #ifdef HAVE_WIN32_THREADS #include #ifndef HAVE_COMPILER_TLS #include #endif #endif #ifdef HAVE_BEOS_THREADS #include #include #endif #if defined(SOLARIS) #include #endif /* #define DEBUG_THREADS */ #ifdef HAVE_PTHREAD_H static int libxml_is_threaded = -1; #ifdef __GNUC__ #ifdef linux #if (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || (__GNUC__ > 3) extern int pthread_once (pthread_once_t *__once_control, void (*__init_routine) (void)) __attribute((weak)); extern void *pthread_getspecific (pthread_key_t __key) __attribute((weak)); extern int pthread_setspecific (pthread_key_t __key, __const void *__pointer) __attribute((weak)); extern int pthread_key_create (pthread_key_t *__key, void (*__destr_function) (void *)) __attribute((weak)); extern int pthread_mutex_init () __attribute((weak)); extern int pthread_mutex_destroy () __attribute((weak)); extern int pthread_mutex_lock () __attribute((weak)); extern int pthread_mutex_unlock () __attribute((weak)); extern int pthread_cond_init () __attribute((weak)); extern int pthread_equal () __attribute((weak)); extern pthread_t pthread_self () __attribute((weak)); extern int pthread_key_create () __attribute((weak)); extern int pthread_cond_signal () __attribute((weak)); #endif #endif /* linux */ #endif /* __GNUC__ */ #endif /* HAVE_PTHREAD_H */ /* * TODO: this module still uses malloc/free and not xmlMalloc/xmlFree * to avoid some crazyness since xmlMalloc/xmlFree may actually * be hosted on allocated blocks needing them for the allocation ... */ /* * xmlMutex are a simple mutual exception locks */ struct _xmlMutex { #ifdef HAVE_PTHREAD_H pthread_mutex_t lock; #elif defined HAVE_WIN32_THREADS HANDLE mutex; #elif defined HAVE_BEOS_THREADS sem_id sem; thread_id tid; #else int empty; #endif }; /* * xmlRMutex are reentrant mutual exception locks */ struct _xmlRMutex { #ifdef HAVE_PTHREAD_H pthread_mutex_t lock; unsigned int held; unsigned int waiters; pthread_t tid; pthread_cond_t cv; #elif defined HAVE_WIN32_THREADS CRITICAL_SECTION cs; unsigned int count; #elif defined HAVE_BEOS_THREADS xmlMutexPtr lock; thread_id tid; int32 count; #else int empty; #endif }; /* * This module still has some internal static data. * - xmlLibraryLock a global lock * - globalkey used for per-thread data */ #ifdef HAVE_PTHREAD_H static pthread_key_t globalkey; static pthread_t mainthread; static pthread_once_t once_control = PTHREAD_ONCE_INIT; #elif defined HAVE_WIN32_THREADS #if defined(HAVE_COMPILER_TLS) static __declspec(thread) xmlGlobalState tlstate; static __declspec(thread) int tlstate_inited = 0; #else /* HAVE_COMPILER_TLS */ static DWORD globalkey = TLS_OUT_OF_INDEXES; #endif /* HAVE_COMPILER_TLS */ static DWORD mainthread; static struct { DWORD done; DWORD control; } run_once = { 0, 0 }; /* endif HAVE_WIN32_THREADS */ #elif defined HAVE_BEOS_THREADS int32 globalkey = 0; thread_id mainthread = 0; int32 run_once_init = 0; #endif static xmlRMutexPtr xmlLibraryLock = NULL; #ifdef LIBXML_THREAD_ENABLED static void xmlOnceInit(void); #endif /** * xmlNewMutex: * * xmlNewMutex() is used to allocate a libxml2 token struct for use in * synchronizing access to data. * * Returns a new simple mutex pointer or NULL in case of error */ xmlMutexPtr xmlNewMutex(void) { xmlMutexPtr tok; if ((tok = malloc(sizeof(xmlMutex))) == NULL) return (NULL); #ifdef HAVE_PTHREAD_H if (libxml_is_threaded != 0) pthread_mutex_init(&tok->lock, NULL); #elif defined HAVE_WIN32_THREADS tok->mutex = CreateMutex(NULL, FALSE, NULL); #elif defined HAVE_BEOS_THREADS if ((tok->sem = create_sem(1, "xmlMutex")) < B_OK) { free(tok); return NULL; } tok->tid = -1; #endif return (tok); } /** * xmlFreeMutex: * @tok: the simple mutex * * xmlFreeMutex() is used to reclaim resources associated with a libxml2 token * struct. */ void xmlFreeMutex(xmlMutexPtr tok) { if (tok == NULL) return; #ifdef HAVE_PTHREAD_H if (libxml_is_threaded != 0) pthread_mutex_destroy(&tok->lock); #elif defined HAVE_WIN32_THREADS CloseHandle(tok->mutex); #elif defined HAVE_BEOS_THREADS delete_sem(tok->sem); #endif free(tok); } /** * xmlMutexLock: * @tok: the simple mutex * * xmlMutexLock() is used to lock a libxml2 token. */ void xmlMutexLock(xmlMutexPtr tok) { if (tok == NULL) return; #ifdef HAVE_PTHREAD_H if (libxml_is_threaded != 0) pthread_mutex_lock(&tok->lock); #elif defined HAVE_WIN32_THREADS WaitForSingleObject(tok->mutex, INFINITE); #elif defined HAVE_BEOS_THREADS if (acquire_sem(tok->sem) != B_NO_ERROR) { #ifdef DEBUG_THREADS xmlGenericError(xmlGenericErrorContext, "xmlMutexLock():BeOS:Couldn't aquire semaphore\n"); exit(); #endif } tok->tid = find_thread(NULL); #endif } /** * xmlMutexUnlock: * @tok: the simple mutex * * xmlMutexUnlock() is used to unlock a libxml2 token. */ void xmlMutexUnlock(xmlMutexPtr tok) { if (tok == NULL) return; #ifdef HAVE_PTHREAD_H if (libxml_is_threaded != 0) pthread_mutex_unlock(&tok->lock); #elif defined HAVE_WIN32_THREADS ReleaseMutex(tok->mutex); #elif defined HAVE_BEOS_THREADS if (tok->tid == find_thread(NULL)) { tok->tid = -1; release_sem(tok->sem); } #endif } /** * xmlNewRMutex: * * xmlRNewMutex() is used to allocate a reentrant mutex for use in * synchronizing access to data. token_r is a re-entrant lock and thus useful * for synchronizing access to data structures that may be manipulated in a * recursive fashion. * * Returns the new reentrant mutex pointer or NULL in case of error */ xmlRMutexPtr xmlNewRMutex(void) { xmlRMutexPtr tok; if ((tok = malloc(sizeof(xmlRMutex))) == NULL) return (NULL); #ifdef HAVE_PTHREAD_H if (libxml_is_threaded != 0) { pthread_mutex_init(&tok->lock, NULL); tok->held = 0; tok->waiters = 0; pthread_cond_init(&tok->cv, NULL); } #elif defined HAVE_WIN32_THREADS InitializeCriticalSection(&tok->cs); tok->count = 0; #elif defined HAVE_BEOS_THREADS if ((tok->lock = xmlNewMutex()) == NULL) { free(tok); return NULL; } tok->count = 0; #endif return (tok); } /** * xmlFreeRMutex: * @tok: the reentrant mutex * * xmlRFreeMutex() is used to reclaim resources associated with a * reentrant mutex. */ void xmlFreeRMutex(xmlRMutexPtr tok ATTRIBUTE_UNUSED) { if (tok == NULL) return; #ifdef HAVE_PTHREAD_H if (libxml_is_threaded != 0) { pthread_mutex_destroy(&tok->lock); pthread_cond_destroy(&tok->cv); } #elif defined HAVE_WIN32_THREADS DeleteCriticalSection(&tok->cs); #elif defined HAVE_BEOS_THREADS xmlFreeMutex(tok->lock); #endif free(tok); } /** * xmlRMutexLock: * @tok: the reentrant mutex * * xmlRMutexLock() is used to lock a libxml2 token_r. */ void xmlRMutexLock(xmlRMutexPtr tok) { if (tok == NULL) return; #ifdef HAVE_PTHREAD_H if (libxml_is_threaded == 0) return; pthread_mutex_lock(&tok->lock); if (tok->held) { if (pthread_equal(tok->tid, pthread_self())) { tok->held++; pthread_mutex_unlock(&tok->lock); return; } else { tok->waiters++; while (tok->held) pthread_cond_wait(&tok->cv, &tok->lock); tok->waiters--; } } tok->tid = pthread_self(); tok->held = 1; pthread_mutex_unlock(&tok->lock); #elif defined HAVE_WIN32_THREADS EnterCriticalSection(&tok->cs); ++tok->count; #elif defined HAVE_BEOS_THREADS if (tok->lock->tid == find_thread(NULL)) { tok->count++; return; } else { xmlMutexLock(tok->lock); tok->count = 1; } #endif } /** * xmlRMutexUnlock: * @tok: the reentrant mutex * * xmlRMutexUnlock() is used to unlock a libxml2 token_r. */ void xmlRMutexUnlock(xmlRMutexPtr tok ATTRIBUTE_UNUSED) { if (tok == NULL) return; #ifdef HAVE_PTHREAD_H if (libxml_is_threaded == 0) return; pthread_mutex_lock(&tok->lock); tok->held--; if (tok->held == 0) { if (tok->waiters) pthread_cond_signal(&tok->cv); tok->tid = 0; } pthread_mutex_unlock(&tok->lock); #elif defined HAVE_WIN32_THREADS if (!--tok->count) LeaveCriticalSection(&tok->cs); #elif defined HAVE_BEOS_THREADS if (tok->lock->tid == find_thread(NULL)) { tok->count--; if (tok->count == 0) { xmlMutexUnlock(tok->lock); } return; } #endif } /************************************************************************ * * * Per thread global state handling * * * ************************************************************************/ #ifdef LIBXML_THREAD_ENABLED #ifdef xmlLastError #undef xmlLastError #endif /** * xmlFreeGlobalState: * @state: a thread global state * * xmlFreeGlobalState() is called when a thread terminates with a non-NULL * global state. It is is used here to reclaim memory resources. */ static void xmlFreeGlobalState(void *state) { xmlGlobalState *gs = (xmlGlobalState *) state; /* free any memory allocated in the thread's xmlLastError */ xmlResetError(&(gs->xmlLastError)); free(state); } /** * xmlNewGlobalState: * * xmlNewGlobalState() allocates a global state. This structure is used to * hold all data for use by a thread when supporting backwards compatibility * of libxml2 to pre-thread-safe behaviour. * * Returns the newly allocated xmlGlobalStatePtr or NULL in case of error */ static xmlGlobalStatePtr xmlNewGlobalState(void) { xmlGlobalState *gs; gs = malloc(sizeof(xmlGlobalState)); if (gs == NULL) return(NULL); memset(gs, 0, sizeof(xmlGlobalState)); xmlInitializeGlobalState(gs); return (gs); } #endif /* LIBXML_THREAD_ENABLED */ #ifdef HAVE_WIN32_THREADS #if !defined(HAVE_COMPILER_TLS) #if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL) typedef struct _xmlGlobalStateCleanupHelperParams { HANDLE thread; void *memory; } xmlGlobalStateCleanupHelperParams; static void XMLCDECL xmlGlobalStateCleanupHelper (void *p) { xmlGlobalStateCleanupHelperParams *params = (xmlGlobalStateCleanupHelperParams *) p; WaitForSingleObject(params->thread, INFINITE); CloseHandle(params->thread); xmlFreeGlobalState(params->memory); free(params); _endthread(); } #else /* LIBXML_STATIC && !LIBXML_STATIC_FOR_DLL */ typedef struct _xmlGlobalStateCleanupHelperParams { void *memory; struct _xmlGlobalStateCleanupHelperParams * prev; struct _xmlGlobalStateCleanupHelperParams * next; } xmlGlobalStateCleanupHelperParams; static xmlGlobalStateCleanupHelperParams * cleanup_helpers_head = NULL; static CRITICAL_SECTION cleanup_helpers_cs; #endif /* LIBXMLSTATIC && !LIBXML_STATIC_FOR_DLL */ #endif /* HAVE_COMPILER_TLS */ #endif /* HAVE_WIN32_THREADS */ #if defined HAVE_BEOS_THREADS /** * xmlGlobalStateCleanup: * @data: unused parameter * * Used for Beos only */ void xmlGlobalStateCleanup(void *data) { void *globalval = tls_get(globalkey); if (globalval != NULL) xmlFreeGlobalState(globalval); } #endif /** * xmlGetGlobalState: * * xmlGetGlobalState() is called to retrieve the global state for a thread. * * Returns the thread global state or NULL in case of error */ xmlGlobalStatePtr xmlGetGlobalState(void) { #ifdef HAVE_PTHREAD_H xmlGlobalState *globalval; if (libxml_is_threaded == 0) return(NULL); pthread_once(&once_control, xmlOnceInit); if ((globalval = (xmlGlobalState *) pthread_getspecific(globalkey)) == NULL) { xmlGlobalState *tsd = xmlNewGlobalState(); pthread_setspecific(globalkey, tsd); return (tsd); } return (globalval); #elif defined HAVE_WIN32_THREADS #if defined(HAVE_COMPILER_TLS) if (!tlstate_inited) { tlstate_inited = 1; xmlInitializeGlobalState(&tlstate); } return &tlstate; #else /* HAVE_COMPILER_TLS */ xmlGlobalState *globalval; xmlGlobalStateCleanupHelperParams * p; xmlOnceInit(); #if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL) globalval = (xmlGlobalState *)TlsGetValue(globalkey); #else p = (xmlGlobalStateCleanupHelperParams*)TlsGetValue(globalkey); globalval = (xmlGlobalState *)(p ? p->memory : NULL); #endif if (globalval == NULL) { xmlGlobalState *tsd = xmlNewGlobalState(); p = (xmlGlobalStateCleanupHelperParams *) malloc(sizeof(xmlGlobalStateCleanupHelperParams)); p->memory = tsd; #if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL) DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &p->thread, 0, TRUE, DUPLICATE_SAME_ACCESS); TlsSetValue(globalkey, tsd); _beginthread(xmlGlobalStateCleanupHelper, 0, p); #else EnterCriticalSection(&cleanup_helpers_cs); if (cleanup_helpers_head != NULL) { cleanup_helpers_head->prev = p; } p->next = cleanup_helpers_head; p->prev = NULL; cleanup_helpers_head = p; TlsSetValue(globalkey, p); LeaveCriticalSection(&cleanup_helpers_cs); #endif return (tsd); } return (globalval); #endif /* HAVE_COMPILER_TLS */ #elif defined HAVE_BEOS_THREADS xmlGlobalState *globalval; xmlOnceInit(); if ((globalval = (xmlGlobalState *) tls_get(globalkey)) == NULL) { xmlGlobalState *tsd = xmlNewGlobalState(); tls_set(globalkey, tsd); on_exit_thread(xmlGlobalStateCleanup, NULL); return (tsd); } return (globalval); #else return(NULL); #endif } /************************************************************************ * * * Library wide thread interfaces * * * ************************************************************************/ /** * xmlGetThreadId: * * xmlGetThreadId() find the current thread ID number * * Returns the current thread ID number */ int xmlGetThreadId(void) { #ifdef HAVE_PTHREAD_H if (libxml_is_threaded == 0) return(0); return((int) pthread_self()); #elif defined HAVE_WIN32_THREADS return GetCurrentThreadId(); #elif defined HAVE_BEOS_THREADS return find_thread(NULL); #else return((int) 0); #endif } /** * xmlIsMainThread: * * xmlIsMainThread() check whether the current thread is the main thread. * * Returns 1 if the current thread is the main thread, 0 otherwise */ int xmlIsMainThread(void) { #ifdef HAVE_PTHREAD_H if (libxml_is_threaded == -1) xmlInitThreads(); if (libxml_is_threaded == 0) return(1); pthread_once(&once_control, xmlOnceInit); #elif defined HAVE_WIN32_THREADS xmlOnceInit (); #elif defined HAVE_BEOS_THREADS xmlOnceInit(); #endif #ifdef DEBUG_THREADS xmlGenericError(xmlGenericErrorContext, "xmlIsMainThread()\n"); #endif #ifdef HAVE_PTHREAD_H return(mainthread == pthread_self()); #elif defined HAVE_WIN32_THREADS return(mainthread == GetCurrentThreadId ()); #elif defined HAVE_BEOS_THREADS return(mainthread == find_thread(NULL)); #else return(1); #endif } /** * xmlLockLibrary: * * xmlLockLibrary() is used to take out a re-entrant lock on the libxml2 * library. */ void xmlLockLibrary(void) { #ifdef DEBUG_THREADS xmlGenericError(xmlGenericErrorContext, "xmlLockLibrary()\n"); #endif xmlRMutexLock(xmlLibraryLock); } /** * xmlUnlockLibrary: * * xmlUnlockLibrary() is used to release a re-entrant lock on the libxml2 * library. */ void xmlUnlockLibrary(void) { #ifdef DEBUG_THREADS xmlGenericError(xmlGenericErrorContext, "xmlUnlockLibrary()\n"); #endif xmlRMutexUnlock(xmlLibraryLock); } /** * xmlInitThreads: * * xmlInitThreads() is used to to initialize all the thread related * data of the libxml2 library. */ void xmlInitThreads(void) { #ifdef DEBUG_THREADS xmlGenericError(xmlGenericErrorContext, "xmlInitThreads()\n"); #endif #if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL)) InitializeCriticalSection(&cleanup_helpers_cs); #endif #ifdef HAVE_PTHREAD_H if (libxml_is_threaded == -1) { if ((pthread_once != NULL) && (pthread_getspecific != NULL) && (pthread_setspecific != NULL) && (pthread_key_create != NULL) && (pthread_mutex_init != NULL) && (pthread_mutex_destroy != NULL) && (pthread_mutex_lock != NULL) && (pthread_mutex_unlock != NULL) && (pthread_cond_init != NULL) && (pthread_equal != NULL) && (pthread_self != NULL) && (pthread_key_create != NULL) && (pthread_cond_signal != NULL)) { libxml_is_threaded = 1; /* fprintf(stderr, "Running multithreaded\n"); */ } else { /* fprintf(stderr, "Running without multithread\n"); */ libxml_is_threaded = 0; } } #endif } /** * xmlCleanupThreads: * * xmlCleanupThreads() is used to to cleanup all the thread related * data of the libxml2 library once processing has ended. */ void xmlCleanupThreads(void) { #ifdef DEBUG_THREADS xmlGenericError(xmlGenericErrorContext, "xmlCleanupThreads()\n"); #endif #if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL)) if (globalkey != TLS_OUT_OF_INDEXES) { xmlGlobalStateCleanupHelperParams * p; EnterCriticalSection(&cleanup_helpers_cs); p = cleanup_helpers_head; while (p != NULL) { xmlGlobalStateCleanupHelperParams * temp = p; p = p->next; xmlFreeGlobalState(temp->memory); free(temp); } cleanup_helpers_head = 0; LeaveCriticalSection(&cleanup_helpers_cs); TlsFree(globalkey); globalkey = TLS_OUT_OF_INDEXES; } DeleteCriticalSection(&cleanup_helpers_cs); #endif } #ifdef LIBXML_THREAD_ENABLED /** * xmlOnceInit * * xmlOnceInit() is used to initialize the value of mainthread for use * in other routines. This function should only be called using * pthread_once() in association with the once_control variable to ensure * that the function is only called once. See man pthread_once for more * details. */ static void xmlOnceInit(void) { #ifdef HAVE_PTHREAD_H (void) pthread_key_create(&globalkey, xmlFreeGlobalState); mainthread = pthread_self(); #endif #if defined(HAVE_WIN32_THREADS) if (!run_once.done) { if (InterlockedIncrement(&run_once.control) == 1) { #if !defined(HAVE_COMPILER_TLS) globalkey = TlsAlloc(); #endif mainthread = GetCurrentThreadId(); run_once.done = 1; } else { /* Another thread is working; give up our slice and * wait until they're done. */ while (!run_once.done) Sleep(0); } } #endif #ifdef HAVE_BEOS_THREADS if (atomic_add(&run_once_init, 1) == 0) { globalkey = tls_allocate(); tls_set(globalkey, NULL); mainthread = find_thread(NULL); } else atomic_add(&run_once_init, -1); #endif } #endif /** * DllMain: * @hinstDLL: handle to DLL instance * @fdwReason: Reason code for entry * @lpvReserved: generic pointer (depends upon reason code) * * Entry point for Windows library. It is being used to free thread-specific * storage. * * Returns TRUE always */ #if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL)) #if defined(LIBXML_STATIC_FOR_DLL) BOOL WINAPI xmlDllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) #else BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) #endif { switch(fdwReason) { case DLL_THREAD_DETACH: if (globalkey != TLS_OUT_OF_INDEXES) { xmlGlobalState *globalval = NULL; xmlGlobalStateCleanupHelperParams * p = (xmlGlobalStateCleanupHelperParams*)TlsGetValue(globalkey); globalval = (xmlGlobalState *)(p ? p->memory : NULL); if (globalval) { xmlFreeGlobalState(globalval); TlsSetValue(globalkey,NULL); } if (p) { EnterCriticalSection(&cleanup_helpers_cs); if (p == cleanup_helpers_head) cleanup_helpers_head = p->next; else p->prev->next = p->next; if (p->next != NULL) p->next->prev = p->prev; LeaveCriticalSection(&cleanup_helpers_cs); free(p); } } break; } return TRUE; } #endif #define bottom_threads #include "elfgcchack.h" xdmf-2.1.dfsg.1/Utilities/vtklibxml2/trionan.h0000644000175000017500000000407511606020250022417 0ustar amckinstryamckinstry/************************************************************************* * * Id: trionan.h 2026 2003-08-06 04:43:55Z wbrack * * Copyright (C) 2001 Bjorn Reese * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER. * ************************************************************************/ #ifndef TRIO_NAN_H #define TRIO_NAN_H #include "triodef.h" #ifdef __cplusplus extern "C" { #endif enum { TRIO_FP_INFINITE, TRIO_FP_NAN, TRIO_FP_NORMAL, TRIO_FP_SUBNORMAL, TRIO_FP_ZERO }; /* * Return NaN (Not-a-Number). */ TRIO_PUBLIC double trio_nan TRIO_PROTO((void)); /* * Return positive infinity. */ TRIO_PUBLIC double trio_pinf TRIO_PROTO((void)); /* * Return negative infinity. */ TRIO_PUBLIC double trio_ninf TRIO_PROTO((void)); /* * Return negative zero. */ TRIO_PUBLIC double trio_nzero TRIO_PROTO((TRIO_NOARGS)); /* * If number is a NaN return non-zero, otherwise return zero. */ TRIO_PUBLIC int trio_isnan TRIO_PROTO((double number)); /* * If number is positive infinity return 1, if number is negative * infinity return -1, otherwise return 0. */ TRIO_PUBLIC int trio_isinf TRIO_PROTO((double number)); /* * If number is finite return non-zero, otherwise return zero. */ #if 0 /* Temporary fix - these 2 routines not used in libxml */ TRIO_PUBLIC int trio_isfinite TRIO_PROTO((double number)); TRIO_PUBLIC int trio_fpclassify TRIO_PROTO((double number)); #endif TRIO_PUBLIC int trio_signbit TRIO_PROTO((double number)); TRIO_PUBLIC int trio_fpclassify_and_signbit TRIO_PROTO((double number, int *is_negative)); #ifdef __cplusplus } #endif #endif /* TRIO_NAN_H */ xdmf-2.1.dfsg.1/Utilities/vtklibxml2/xmlIO.c0000644000175000017500000032335611606020250021776 0ustar amckinstryamckinstry/* * xmlIO.c : implementation of the I/O interfaces used by the parser * * See Copyright for the status of this software. * * daniel@veillard.com * * 14 Nov 2000 ht - for VMS, truncated name of long functions to under 32 char */ #define IN_LIBXML #include "libxml.h" #include #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #include "vtk_libxml2_zlib.h" #ifdef WIN32 #include #endif /*--------------------------------------------------------------------------*/ /* VTK MODIFICATION: When building on cygwin with -mwin32 we get _WIN32 defined. If -mno-cygwin is not given then __CYGWIN__ is still defined. This is the case when VTK builds in cygwin. The cygwin API does not provide _wfopen or _wstat, and libxml2 does not seem to have accounted for this upstream. We work around the unresolved symbols by providing them here. We simply return failure so that the routines below fall back to the single-width API provided by cygwin. */ #if defined(_WIN32) && defined(__CYGWIN__) static FILE* _wfopen(const wchar_t* path, const wchar_t* mode) { (void)path; (void)mode; return 0; } static int _wstat(const wchar_t* path, struct _stat* info) { (void)path; (void)info; return -1; } #endif /*--------------------------------------------------------------------------*/ /* Figure a portable way to know if a file is a directory. */ #ifndef HAVE_STAT # ifdef HAVE__STAT /* MS C library seems to define stat and _stat. The definition is identical. Still, mapping them to each other causes a warning. */ # ifndef _MSC_VER # define stat(x,y) _stat(x,y) # endif # define HAVE_STAT # endif #else # ifdef HAVE__STAT # if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) # define stat _stat # endif # endif #endif #ifdef HAVE_STAT # ifndef S_ISDIR # ifdef _S_ISDIR # define S_ISDIR(x) _S_ISDIR(x) # else # ifdef S_IFDIR # ifndef S_IFMT # ifdef _S_IFMT # define S_IFMT _S_IFMT # endif # endif # ifdef S_IFMT # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) # endif # endif # endif # endif #endif #include #include #include #include #include #include #include #include #ifdef LIBXML_CATALOG_ENABLED #include #endif #include /* #define VERBOSE_FAILURE */ /* #define DEBUG_EXTERNAL_ENTITIES */ /* #define DEBUG_INPUT */ #ifdef DEBUG_INPUT #define MINLEN 40 #else #define MINLEN 4000 #endif /* * Input I/O callback sets */ typedef struct _xmlInputCallback { xmlInputMatchCallback matchcallback; xmlInputOpenCallback opencallback; xmlInputReadCallback readcallback; xmlInputCloseCallback closecallback; } xmlInputCallback; #define MAX_INPUT_CALLBACK 15 static xmlInputCallback xmlInputCallbackTable[MAX_INPUT_CALLBACK]; static int xmlInputCallbackNr = 0; static int xmlInputCallbackInitialized = 0; #ifdef LIBXML_OUTPUT_ENABLED /* * Output I/O callback sets */ typedef struct _xmlOutputCallback { xmlOutputMatchCallback matchcallback; xmlOutputOpenCallback opencallback; xmlOutputWriteCallback writecallback; xmlOutputCloseCallback closecallback; } xmlOutputCallback; #define MAX_OUTPUT_CALLBACK 15 static xmlOutputCallback xmlOutputCallbackTable[MAX_OUTPUT_CALLBACK]; static int xmlOutputCallbackNr = 0; static int xmlOutputCallbackInitialized = 0; #endif /* LIBXML_OUTPUT_ENABLED */ /************************************************************************ * * * Tree memory error handler * * * ************************************************************************/ static const char *IOerr[] = { "Unknown IO error", /* UNKNOWN */ "Permission denied", /* EACCES */ "Resource temporarily unavailable",/* EAGAIN */ "Bad file descriptor", /* EBADF */ "Bad message", /* EBADMSG */ "Resource busy", /* EBUSY */ "Operation canceled", /* ECANCELED */ "No child processes", /* ECHILD */ "Resource deadlock avoided",/* EDEADLK */ "Domain error", /* EDOM */ "File exists", /* EEXIST */ "Bad address", /* EFAULT */ "File too large", /* EFBIG */ "Operation in progress", /* EINPROGRESS */ "Interrupted function call",/* EINTR */ "Invalid argument", /* EINVAL */ "Input/output error", /* EIO */ "Is a directory", /* EISDIR */ "Too many open files", /* EMFILE */ "Too many links", /* EMLINK */ "Inappropriate message buffer length",/* EMSGSIZE */ "Filename too long", /* ENAMETOOLONG */ "Too many open files in system",/* ENFILE */ "No such device", /* ENODEV */ "No such file or directory",/* ENOENT */ "Exec format error", /* ENOEXEC */ "No locks available", /* ENOLCK */ "Not enough space", /* ENOMEM */ "No space left on device", /* ENOSPC */ "Function not implemented", /* ENOSYS */ "Not a directory", /* ENOTDIR */ "Directory not empty", /* ENOTEMPTY */ "Not supported", /* ENOTSUP */ "Inappropriate I/O control operation",/* ENOTTY */ "No such device or address",/* ENXIO */ "Operation not permitted", /* EPERM */ "Broken pipe", /* EPIPE */ "Result too large", /* ERANGE */ "Read-only file system", /* EROFS */ "Invalid seek", /* ESPIPE */ "No such process", /* ESRCH */ "Operation timed out", /* ETIMEDOUT */ "Improper link", /* EXDEV */ "Attempt to load network entity %s", /* XML_IO_NETWORK_ATTEMPT */ "encoder error", /* XML_IO_ENCODER */ "flush error", "write error", "no input", "buffer full", "loading error", "not a socket", /* ENOTSOCK */ "already connected", /* EISCONN */ "connection refused", /* ECONNREFUSED */ "unreachable network", /* ENETUNREACH */ "adddress in use", /* EADDRINUSE */ "already in use", /* EALREADY */ "unknown address familly", /* EAFNOSUPPORT */ }; #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) /** * __xmlIOWin32UTF8ToWChar: * @u8String: uft-8 string * * Convert a string from utf-8 to wchar (WINDOWS ONLY!) */ static wchar_t * __xmlIOWin32UTF8ToWChar(const char *u8String) { wchar_t *wString = NULL; if (u8String) { int wLen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, u8String, -1, NULL, 0); if (wLen) { wString = xmlMalloc(wLen * sizeof(wchar_t)); if (wString) { if (MultiByteToWideChar (CP_UTF8, 0, u8String, -1, wString, wLen) == 0) { xmlFree(wString); wString = NULL; } } } } return wString; } #endif /** * xmlIOErrMemory: * @extra: extra informations * * Handle an out of memory condition */ static void xmlIOErrMemory(const char *extra) { __xmlSimpleError(XML_FROM_IO, XML_ERR_NO_MEMORY, NULL, NULL, extra); } /** * __xmlIOErr: * @code: the error number * @ * @extra: extra informations * * Handle an I/O error */ void __xmlIOErr(int domain, int code, const char *extra) { unsigned int idx; if (code == 0) { #ifdef HAVE_ERRNO_H if (errno == 0) code = 0; #ifdef EACCES else if (errno == EACCES) code = XML_IO_EACCES; #endif #ifdef EAGAIN else if (errno == EAGAIN) code = XML_IO_EAGAIN; #endif #ifdef EBADF else if (errno == EBADF) code = XML_IO_EBADF; #endif #ifdef EBADMSG else if (errno == EBADMSG) code = XML_IO_EBADMSG; #endif #ifdef EBUSY else if (errno == EBUSY) code = XML_IO_EBUSY; #endif #ifdef ECANCELED else if (errno == ECANCELED) code = XML_IO_ECANCELED; #endif #ifdef ECHILD else if (errno == ECHILD) code = XML_IO_ECHILD; #endif #ifdef EDEADLK else if (errno == EDEADLK) code = XML_IO_EDEADLK; #endif #ifdef EDOM else if (errno == EDOM) code = XML_IO_EDOM; #endif #ifdef EEXIST else if (errno == EEXIST) code = XML_IO_EEXIST; #endif #ifdef EFAULT else if (errno == EFAULT) code = XML_IO_EFAULT; #endif #ifdef EFBIG else if (errno == EFBIG) code = XML_IO_EFBIG; #endif #ifdef EINPROGRESS else if (errno == EINPROGRESS) code = XML_IO_EINPROGRESS; #endif #ifdef EINTR else if (errno == EINTR) code = XML_IO_EINTR; #endif #ifdef EINVAL else if (errno == EINVAL) code = XML_IO_EINVAL; #endif #ifdef EIO else if (errno == EIO) code = XML_IO_EIO; #endif #ifdef EISDIR else if (errno == EISDIR) code = XML_IO_EISDIR; #endif #ifdef EMFILE else if (errno == EMFILE) code = XML_IO_EMFILE; #endif #ifdef EMLINK else if (errno == EMLINK) code = XML_IO_EMLINK; #endif #ifdef EMSGSIZE else if (errno == EMSGSIZE) code = XML_IO_EMSGSIZE; #endif #ifdef ENAMETOOLONG else if (errno == ENAMETOOLONG) code = XML_IO_ENAMETOOLONG; #endif #ifdef ENFILE else if (errno == ENFILE) code = XML_IO_ENFILE; #endif #ifdef ENODEV else if (errno == ENODEV) code = XML_IO_ENODEV; #endif #ifdef ENOENT else if (errno == ENOENT) code = XML_IO_ENOENT; #endif #ifdef ENOEXEC else if (errno == ENOEXEC) code = XML_IO_ENOEXEC; #endif #ifdef ENOLCK else if (errno == ENOLCK) code = XML_IO_ENOLCK; #endif #ifdef ENOMEM else if (errno == ENOMEM) code = XML_IO_ENOMEM; #endif #ifdef ENOSPC else if (errno == ENOSPC) code = XML_IO_ENOSPC; #endif #ifdef ENOSYS else if (errno == ENOSYS) code = XML_IO_ENOSYS; #endif #ifdef ENOTDIR else if (errno == ENOTDIR) code = XML_IO_ENOTDIR; #endif #ifdef ENOTEMPTY else if (errno == ENOTEMPTY) code = XML_IO_ENOTEMPTY; #endif #ifdef ENOTSUP else if (errno == ENOTSUP) code = XML_IO_ENOTSUP; #endif #ifdef ENOTTY else if (errno == ENOTTY) code = XML_IO_ENOTTY; #endif #ifdef ENXIO else if (errno == ENXIO) code = XML_IO_ENXIO; #endif #ifdef EPERM else if (errno == EPERM) code = XML_IO_EPERM; #endif #ifdef EPIPE else if (errno == EPIPE) code = XML_IO_EPIPE; #endif #ifdef ERANGE else if (errno == ERANGE) code = XML_IO_ERANGE; #endif #ifdef EROFS else if (errno == EROFS) code = XML_IO_EROFS; #endif #ifdef ESPIPE else if (errno == ESPIPE) code = XML_IO_ESPIPE; #endif #ifdef ESRCH else if (errno == ESRCH) code = XML_IO_ESRCH; #endif #ifdef ETIMEDOUT else if (errno == ETIMEDOUT) code = XML_IO_ETIMEDOUT; #endif #ifdef EXDEV else if (errno == EXDEV) code = XML_IO_EXDEV; #endif #ifdef ENOTSOCK else if (errno == ENOTSOCK) code = XML_IO_ENOTSOCK; #endif #ifdef EISCONN else if (errno == EISCONN) code = XML_IO_EISCONN; #endif #ifdef ECONNREFUSED else if (errno == ECONNREFUSED) code = XML_IO_ECONNREFUSED; #endif #ifdef ETIMEDOUT else if (errno == ETIMEDOUT) code = XML_IO_ETIMEDOUT; #endif #ifdef ENETUNREACH else if (errno == ENETUNREACH) code = XML_IO_ENETUNREACH; #endif #ifdef EADDRINUSE else if (errno == EADDRINUSE) code = XML_IO_EADDRINUSE; #endif #ifdef EINPROGRESS else if (errno == EINPROGRESS) code = XML_IO_EINPROGRESS; #endif #ifdef EALREADY else if (errno == EALREADY) code = XML_IO_EALREADY; #endif #ifdef EAFNOSUPPORT else if (errno == EAFNOSUPPORT) code = XML_IO_EAFNOSUPPORT; #endif else code = XML_IO_UNKNOWN; #endif /* HAVE_ERRNO_H */ } idx = 0; if (code >= XML_IO_UNKNOWN) idx = code - XML_IO_UNKNOWN; if (idx >= (sizeof(IOerr) / sizeof(IOerr[0]))) idx = 0; __xmlSimpleError(domain, code, NULL, IOerr[idx], extra); } /** * xmlIOErr: * @code: the error number * @extra: extra informations * * Handle an I/O error */ static void xmlIOErr(int code, const char *extra) { __xmlIOErr(XML_FROM_IO, code, extra); } /** * __xmlLoaderErr: * @ctx: the parser context * @extra: extra informations * * Handle a resource access error */ void __xmlLoaderErr(void *ctx, const char *msg, const char *filename) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlStructuredErrorFunc schannel = NULL; xmlGenericErrorFunc channel = NULL; void *data = NULL; xmlErrorLevel level = XML_ERR_ERROR; if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if ((ctxt != NULL) && (ctxt->sax != NULL)) { if (ctxt->validate) { channel = ctxt->sax->error; level = XML_ERR_ERROR; } else { channel = ctxt->sax->warning; level = XML_ERR_WARNING; } if (ctxt->sax->initialized == XML_SAX2_MAGIC) schannel = ctxt->sax->serror; data = ctxt->userData; } __xmlRaiseError(schannel, channel, data, ctxt, NULL, XML_FROM_IO, XML_IO_LOAD_ERROR, level, NULL, 0, filename, NULL, NULL, 0, 0, msg, filename); } /************************************************************************ * * * Tree memory error handler * * * ************************************************************************/ /** * xmlNormalizeWindowsPath: * @path: the input file path * * This function is obsolete. Please see xmlURIFromPath in uri.c for * a better solution. * * Returns a canonicalized version of the path */ xmlChar * xmlNormalizeWindowsPath(const xmlChar *path) { return xmlCanonicPath(path); } /** * xmlCleanupInputCallbacks: * * clears the entire input callback table. this includes the * compiled-in I/O. */ void xmlCleanupInputCallbacks(void) { int i; if (!xmlInputCallbackInitialized) return; for (i = xmlInputCallbackNr - 1; i >= 0; i--) { xmlInputCallbackTable[i].matchcallback = NULL; xmlInputCallbackTable[i].opencallback = NULL; xmlInputCallbackTable[i].readcallback = NULL; xmlInputCallbackTable[i].closecallback = NULL; } xmlInputCallbackNr = 0; xmlInputCallbackInitialized = 0; } /** * xmlPopInputCallbacks: * * Clear the top input callback from the input stack. this includes the * compiled-in I/O. * * Returns the number of input callback registered or -1 in case of error. */ int xmlPopInputCallbacks(void) { if (!xmlInputCallbackInitialized) return(-1); if (xmlInputCallbackNr <= 0) return(-1); xmlInputCallbackNr--; xmlInputCallbackTable[xmlInputCallbackNr].matchcallback = NULL; xmlInputCallbackTable[xmlInputCallbackNr].opencallback = NULL; xmlInputCallbackTable[xmlInputCallbackNr].readcallback = NULL; xmlInputCallbackTable[xmlInputCallbackNr].closecallback = NULL; return(xmlInputCallbackNr); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlCleanupOutputCallbacks: * * clears the entire output callback table. this includes the * compiled-in I/O callbacks. */ void xmlCleanupOutputCallbacks(void) { int i; if (!xmlOutputCallbackInitialized) return; for (i = xmlOutputCallbackNr - 1; i >= 0; i--) { xmlOutputCallbackTable[i].matchcallback = NULL; xmlOutputCallbackTable[i].opencallback = NULL; xmlOutputCallbackTable[i].writecallback = NULL; xmlOutputCallbackTable[i].closecallback = NULL; } xmlOutputCallbackNr = 0; xmlOutputCallbackInitialized = 0; } #endif /* LIBXML_OUTPUT_ENABLED */ /************************************************************************ * * * Standard I/O for file accesses * * * ************************************************************************/ #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) /** * xmlWrapOpenUtf8: * @path: the path in utf-8 encoding * @mode: type of access (0 - read, 1 - write) * * function opens the file specified by @path * */ static FILE* xmlWrapOpenUtf8(const char *path,int mode) { FILE *fd = NULL; wchar_t *wPath; wPath = __xmlIOWin32UTF8ToWChar(path); if(wPath) { fd = _wfopen(wPath, mode ? L"wb" : L"rb"); xmlFree(wPath); } /* maybe path in native encoding */ if(fd == NULL) fd = fopen(path, mode ? "wb" : "rb"); return fd; } /** * xmlWrapStatUtf8: * @path: the path in utf-8 encoding * @info: structure that stores results * * function obtains information about the file or directory * */ static int xmlWrapStatUtf8(const char *path,struct stat *info) { #ifdef HAVE_STAT int retval = -1; wchar_t *wPath; wPath = __xmlIOWin32UTF8ToWChar(path); if (wPath) { retval = _wstat(wPath,info); xmlFree(wPath); } /* maybe path in native encoding */ if(retval < 0) retval = stat(path,info); return retval; #else return -1; #endif } /** * xmlWrapOpenNative: * @path: the path * @mode: type of access (0 - read, 1 - write) * * function opens the file specified by @path * */ static FILE* xmlWrapOpenNative(const char *path,int mode) { return fopen(path,mode ? "wb" : "rb"); } /** * xmlWrapStatNative: * @path: the path * @info: structure that stores results * * function obtains information about the file or directory * */ static int xmlWrapStatNative(const char *path,struct stat *info) { #ifdef HAVE_STAT return stat(path,info); #else return -1; #endif } typedef int (* xmlWrapStatFunc) (const char *f, struct stat *s); static xmlWrapStatFunc xmlWrapStat = xmlWrapStatNative; typedef FILE* (* xmlWrapOpenFunc)(const char *f,int mode); static xmlWrapOpenFunc xmlWrapOpen = xmlWrapOpenNative; /** * xmlInitPlatformSpecificIo: * * Initialize platform specific features. */ static void xmlInitPlatformSpecificIo(void) { static int xmlPlatformIoInitialized = 0; OSVERSIONINFO osvi; if(xmlPlatformIoInitialized) return; osvi.dwOSVersionInfoSize = sizeof(osvi); if(GetVersionEx(&osvi) && (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)) { xmlWrapStat = xmlWrapStatUtf8; xmlWrapOpen = xmlWrapOpenUtf8; } else { xmlWrapStat = xmlWrapStatNative; xmlWrapOpen = xmlWrapOpenNative; } xmlPlatformIoInitialized = 1; return; } #endif /** * xmlCheckFilename: * @path: the path to check * * function checks to see if @path is a valid source * (file, socket...) for XML. * * if stat is not available on the target machine, * returns 1. if stat fails, returns 0 (if calling * stat on the filename fails, it can't be right). * if stat succeeds and the file is a directory, * returns 2. otherwise returns 1. */ int xmlCheckFilename (const char *path) { #ifdef HAVE_STAT struct stat stat_buffer; #endif if (path == NULL) return(0); #ifdef HAVE_STAT #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) if (xmlWrapStat(path, &stat_buffer) == -1) return 0; #else if (stat(path, &stat_buffer) == -1) return 0; #endif #ifdef S_ISDIR if (S_ISDIR(stat_buffer.st_mode)) return 2; #endif #endif /* HAVE_STAT */ return 1; } static int xmlNop(void) { return(0); } /** * xmlFdRead: * @context: the I/O context * @buffer: where to drop data * @len: number of bytes to read * * Read @len bytes to @buffer from the I/O channel. * * Returns the number of bytes written */ static int xmlFdRead (void * context, char * buffer, int len) { int ret; ret = read((int) (long) context, &buffer[0], len); if (ret < 0) xmlIOErr(0, "read()"); return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlFdWrite: * @context: the I/O context * @buffer: where to get data * @len: number of bytes to write * * Write @len bytes from @buffer to the I/O channel. * * Returns the number of bytes written */ static int xmlFdWrite (void * context, const char * buffer, int len) { int ret = 0; if (len > 0) { ret = write((int) (long) context, &buffer[0], len); if (ret < 0) xmlIOErr(0, "write()"); } return(ret); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlFdClose: * @context: the I/O context * * Close an I/O channel * * Returns 0 in case of success and error code otherwise */ static int xmlFdClose (void * context) { int ret; ret = close((int) (long) context); if (ret < 0) xmlIOErr(0, "close()"); return(ret); } /** * xmlFileMatch: * @filename: the URI for matching * * input from FILE * * * Returns 1 if matches, 0 otherwise */ int xmlFileMatch (const char *filename ATTRIBUTE_UNUSED) { return(1); } /** * xmlFileOpen_real: * @filename: the URI for matching * * input from FILE *, supports compressed input * if @filename is " " then the standard input is used * * Returns an I/O context or NULL in case of error */ static void * xmlFileOpen_real (const char *filename) { const char *path = NULL; FILE *fd; if (filename == NULL) return(NULL); if (!strcmp(filename, "-")) { fd = stdin; return((void *) fd); } if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file://localhost/", 17)) #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[17]; #else path = &filename[16]; #endif else if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file:///", 8)) { #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[8]; #else path = &filename[7]; #endif } else path = filename; if (path == NULL) return(NULL); if (!xmlCheckFilename(path)) return(NULL); #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) fd = xmlWrapOpen(path, 0); #else fd = fopen(path, "r"); #endif /* WIN32 */ if (fd == NULL) xmlIOErr(0, path); return((void *) fd); } /** * xmlFileOpen: * @filename: the URI for matching * * Wrapper around xmlFileOpen_real that try it with an unescaped * version of @filename, if this fails fallback to @filename * * Returns a handler or NULL in case or failure */ void * xmlFileOpen (const char *filename) { char *unescaped; void *retval; unescaped = xmlURIUnescapeString(filename, 0, NULL); if (unescaped != NULL) { retval = xmlFileOpen_real(unescaped); xmlFree(unescaped); } else { retval = xmlFileOpen_real(filename); } return retval; } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlFileOpenW: * @filename: the URI for matching * * output to from FILE *, * if @filename is "-" then the standard output is used * * Returns an I/O context or NULL in case of error */ static void * xmlFileOpenW (const char *filename) { const char *path = NULL; FILE *fd; if (!strcmp(filename, "-")) { fd = stdout; return((void *) fd); } if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file://localhost/", 17)) #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[17]; #else path = &filename[16]; #endif else if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file:///", 8)) { #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[8]; #else path = &filename[7]; #endif } else path = filename; if (path == NULL) return(NULL); #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) fd = xmlWrapOpen(path, 1); #else fd = fopen(path, "wb"); #endif /* WIN32 */ if (fd == NULL) xmlIOErr(0, path); return((void *) fd); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlFileRead: * @context: the I/O context * @buffer: where to drop data * @len: number of bytes to write * * Read @len bytes to @buffer from the I/O channel. * * Returns the number of bytes written or < 0 in case of failure */ int xmlFileRead (void * context, char * buffer, int len) { int ret; if ((context == NULL) || (buffer == NULL)) return(-1); ret = fread(&buffer[0], 1, len, (FILE *) context); if (ret < 0) xmlIOErr(0, "fread()"); return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlFileWrite: * @context: the I/O context * @buffer: where to drop data * @len: number of bytes to write * * Write @len bytes from @buffer to the I/O channel. * * Returns the number of bytes written */ static int xmlFileWrite (void * context, const char * buffer, int len) { int items; if ((context == NULL) || (buffer == NULL)) return(-1); items = fwrite(&buffer[0], len, 1, (FILE *) context); if ((items == 0) && (ferror((FILE *) context))) { xmlIOErr(0, "fwrite()"); return(-1); } return(items * len); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlFileClose: * @context: the I/O context * * Close an I/O channel * * Returns 0 or -1 in case of error */ int xmlFileClose (void * context) { FILE *fil; int ret; if (context == NULL) return(-1); fil = (FILE *) context; if ((fil == stdout) || (fil == stderr)) { ret = fflush(fil); if (ret < 0) xmlIOErr(0, "fflush()"); return(0); } if (fil == stdin) return(0); ret = ( fclose((FILE *) context) == EOF ) ? -1 : 0; if (ret < 0) xmlIOErr(0, "fclose()"); return(ret); } /** * xmlFileFlush: * @context: the I/O context * * Flush an I/O channel */ static int xmlFileFlush (void * context) { int ret; if (context == NULL) return(-1); ret = ( fflush((FILE *) context) == EOF ) ? -1 : 0; if (ret < 0) xmlIOErr(0, "fflush()"); return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlBufferWrite: * @context: the xmlBuffer * @buffer: the data to write * @len: number of bytes to write * * Write @len bytes from @buffer to the xml buffer * * Returns the number of bytes written */ static int xmlBufferWrite (void * context, const char * buffer, int len) { int ret; ret = xmlBufferAdd((xmlBufferPtr) context, (const xmlChar *) buffer, len); if (ret != 0) return(-1); return(len); } #endif #ifdef HAVE_ZLIB_H /************************************************************************ * * * I/O for compressed file accesses * * * ************************************************************************/ /** * xmlGzfileMatch: * @filename: the URI for matching * * input from compressed file test * * Returns 1 if matches, 0 otherwise */ static int xmlGzfileMatch (const char *filename ATTRIBUTE_UNUSED) { return(1); } /** * xmlGzfileOpen_real: * @filename: the URI for matching * * input from compressed file open * if @filename is " " then the standard input is used * * Returns an I/O context or NULL in case of error */ static void * xmlGzfileOpen_real (const char *filename) { const char *path = NULL; gzFile fd; if (!strcmp(filename, "-")) { fd = gzdopen(dup(0), "rb"); return((void *) fd); } if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file://localhost/", 17)) #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[17]; #else path = &filename[16]; #endif else if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file:///", 8)) { #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[8]; #else path = &filename[7]; #endif } else path = filename; if (path == NULL) return(NULL); if (!xmlCheckFilename(path)) return(NULL); fd = gzopen(path, "rb"); return((void *) fd); } /** * xmlGzfileOpen: * @filename: the URI for matching * * Wrapper around xmlGzfileOpen if the open fais, it will * try to unescape @filename */ static void * xmlGzfileOpen (const char *filename) { char *unescaped; void *retval; retval = xmlGzfileOpen_real(filename); if (retval == NULL) { unescaped = xmlURIUnescapeString(filename, 0, NULL); if (unescaped != NULL) { retval = xmlGzfileOpen_real(unescaped); } xmlFree(unescaped); } return retval; } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlGzfileOpenW: * @filename: the URI for matching * @compression: the compression factor (0 - 9 included) * * input from compressed file open * if @filename is " " then the standard input is used * * Returns an I/O context or NULL in case of error */ static void * xmlGzfileOpenW (const char *filename, int compression) { const char *path = NULL; char mode[15]; gzFile fd; snprintf(mode, sizeof(mode), "wb%d", compression); if (!strcmp(filename, "-")) { fd = gzdopen(dup(1), mode); return((void *) fd); } if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file://localhost/", 17)) #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[17]; #else path = &filename[16]; #endif else if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file:///", 8)) { #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &filename[8]; #else path = &filename[7]; #endif } else path = filename; if (path == NULL) return(NULL); fd = gzopen(path, mode); return((void *) fd); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlGzfileRead: * @context: the I/O context * @buffer: where to drop data * @len: number of bytes to write * * Read @len bytes to @buffer from the compressed I/O channel. * * Returns the number of bytes written */ static int xmlGzfileRead (void * context, char * buffer, int len) { int ret; ret = gzread((gzFile) context, &buffer[0], len); if (ret < 0) xmlIOErr(0, "gzread()"); return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlGzfileWrite: * @context: the I/O context * @buffer: where to drop data * @len: number of bytes to write * * Write @len bytes from @buffer to the compressed I/O channel. * * Returns the number of bytes written */ static int xmlGzfileWrite (void * context, const char * buffer, int len) { int ret; ret = gzwrite((gzFile) context, (char *) &buffer[0], len); if (ret < 0) xmlIOErr(0, "gzwrite()"); return(ret); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlGzfileClose: * @context: the I/O context * * Close a compressed I/O channel */ static int xmlGzfileClose (void * context) { int ret; ret = (gzclose((gzFile) context) == Z_OK ) ? 0 : -1; if (ret < 0) xmlIOErr(0, "gzclose()"); return(ret); } #endif /* HAVE_ZLIB_H */ #ifdef LIBXML_HTTP_ENABLED /************************************************************************ * * * I/O for HTTP file accesses * * * ************************************************************************/ #ifdef LIBXML_OUTPUT_ENABLED typedef struct xmlIOHTTPWriteCtxt_ { int compression; char * uri; void * doc_buff; } xmlIOHTTPWriteCtxt, *xmlIOHTTPWriteCtxtPtr; #ifdef HAVE_ZLIB_H #define DFLT_WBITS ( -15 ) #define DFLT_MEM_LVL ( 8 ) #define GZ_MAGIC1 ( 0x1f ) #define GZ_MAGIC2 ( 0x8b ) #define LXML_ZLIB_OS_CODE ( 0x03 ) #define INIT_HTTP_BUFF_SIZE ( 32768 ) #define DFLT_ZLIB_RATIO ( 5 ) /* ** Data structure and functions to work with sending compressed data ** via HTTP. */ typedef struct xmlZMemBuff_ { unsigned long size; unsigned long crc; unsigned char * zbuff; z_stream zctrl; } xmlZMemBuff, *xmlZMemBuffPtr; /** * append_reverse_ulong * @buff: Compressed memory buffer * @data: Unsigned long to append * * Append a unsigned long in reverse byte order to the end of the * memory buffer. */ static void append_reverse_ulong( xmlZMemBuff * buff, unsigned long data ) { int idx; if ( buff == NULL ) return; /* ** This is plagiarized from putLong in gzio.c (zlib source) where ** the number "4" is hardcoded. If zlib is ever patched to ** support 64 bit file sizes, this code would need to be patched ** as well. */ for ( idx = 0; idx < 4; idx++ ) { *buff->zctrl.next_out = ( data & 0xff ); data >>= 8; buff->zctrl.next_out++; } return; } /** * * xmlFreeZMemBuff * @buff: The memory buffer context to clear * * Release all the resources associated with the compressed memory buffer. */ static void xmlFreeZMemBuff( xmlZMemBuffPtr buff ) { #ifdef DEBUG_HTTP int z_err; #endif if ( buff == NULL ) return; xmlFree( buff->zbuff ); #ifdef DEBUG_HTTP z_err = deflateEnd( &buff->zctrl ); if ( z_err != Z_OK ) xmlGenericError( xmlGenericErrorContext, "xmlFreeZMemBuff: Error releasing zlib context: %d\n", z_err ); #else deflateEnd( &buff->zctrl ); #endif xmlFree( buff ); return; } /** * xmlCreateZMemBuff *@compression: Compression value to use * * Create a memory buffer to hold the compressed XML document. The * compressed document in memory will end up being identical to what * would be created if gzopen/gzwrite/gzclose were being used to * write the document to disk. The code for the header/trailer data to * the compression is plagiarized from the zlib source files. */ static void * xmlCreateZMemBuff( int compression ) { int z_err; int hdr_lgth; xmlZMemBuffPtr buff = NULL; if ( ( compression < 1 ) || ( compression > 9 ) ) return ( NULL ); /* Create the control and data areas */ buff = xmlMalloc( sizeof( xmlZMemBuff ) ); if ( buff == NULL ) { xmlIOErrMemory("creating buffer context"); return ( NULL ); } (void)memset( buff, 0, sizeof( xmlZMemBuff ) ); buff->size = INIT_HTTP_BUFF_SIZE; buff->zbuff = xmlMalloc( buff->size ); if ( buff->zbuff == NULL ) { xmlFreeZMemBuff( buff ); xmlIOErrMemory("creating buffer"); return ( NULL ); } z_err = deflateInit2( &buff->zctrl, compression, Z_DEFLATED, DFLT_WBITS, DFLT_MEM_LVL, Z_DEFAULT_STRATEGY ); if ( z_err != Z_OK ) { xmlChar msg[500]; xmlFreeZMemBuff( buff ); buff = NULL; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlCreateZMemBuff: %s %d\n", "Error initializing compression context. ZLIB error:", z_err ); xmlIOErr(XML_IO_WRITE, (const char *) msg); return ( NULL ); } /* Set the header data. The CRC will be needed for the trailer */ buff->crc = crc32( 0L, NULL, 0 ); hdr_lgth = snprintf( (char *)buff->zbuff, buff->size, "%c%c%c%c%c%c%c%c%c%c", GZ_MAGIC1, GZ_MAGIC2, Z_DEFLATED, 0, 0, 0, 0, 0, 0, LXML_ZLIB_OS_CODE ); buff->zctrl.next_out = buff->zbuff + hdr_lgth; buff->zctrl.avail_out = buff->size - hdr_lgth; return ( buff ); } /** * xmlZMemBuffExtend * @buff: Buffer used to compress and consolidate data. * @ext_amt: Number of bytes to extend the buffer. * * Extend the internal buffer used to store the compressed data by the * specified amount. * * Returns 0 on success or -1 on failure to extend the buffer. On failure * the original buffer still exists at the original size. */ static int xmlZMemBuffExtend( xmlZMemBuffPtr buff, size_t ext_amt ) { int rc = -1; size_t new_size; size_t cur_used; unsigned char * tmp_ptr = NULL; if ( buff == NULL ) return ( -1 ); else if ( ext_amt == 0 ) return ( 0 ); cur_used = buff->zctrl.next_out - buff->zbuff; new_size = buff->size + ext_amt; #ifdef DEBUG_HTTP if ( cur_used > new_size ) xmlGenericError( xmlGenericErrorContext, "xmlZMemBuffExtend: %s\n%s %d bytes.\n", "Buffer overwrite detected during compressed memory", "buffer extension. Overflowed by", (cur_used - new_size ) ); #endif tmp_ptr = xmlRealloc( buff->zbuff, new_size ); if ( tmp_ptr != NULL ) { rc = 0; buff->size = new_size; buff->zbuff = tmp_ptr; buff->zctrl.next_out = tmp_ptr + cur_used; buff->zctrl.avail_out = new_size - cur_used; } else { xmlChar msg[500]; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlZMemBuffExtend: %s %lu bytes.\n", "Allocation failure extending output buffer to", new_size ); xmlIOErr(XML_IO_WRITE, (const char *) msg); } return ( rc ); } /** * xmlZMemBuffAppend * @buff: Buffer used to compress and consolidate data * @src: Uncompressed source content to append to buffer * @len: Length of source data to append to buffer * * Compress and append data to the internal buffer. The data buffer * will be expanded if needed to store the additional data. * * Returns the number of bytes appended to the buffer or -1 on error. */ static int xmlZMemBuffAppend( xmlZMemBuffPtr buff, const char * src, int len ) { int z_err; size_t min_accept; if ( ( buff == NULL ) || ( src == NULL ) ) return ( -1 ); buff->zctrl.avail_in = len; buff->zctrl.next_in = (unsigned char *)src; while ( buff->zctrl.avail_in > 0 ) { /* ** Extend the buffer prior to deflate call if a reasonable amount ** of output buffer space is not available. */ min_accept = buff->zctrl.avail_in / DFLT_ZLIB_RATIO; if ( buff->zctrl.avail_out <= min_accept ) { if ( xmlZMemBuffExtend( buff, buff->size ) == -1 ) return ( -1 ); } z_err = deflate( &buff->zctrl, Z_NO_FLUSH ); if ( z_err != Z_OK ) { xmlChar msg[500]; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlZMemBuffAppend: %s %d %s - %d", "Compression error while appending", len, "bytes to buffer. ZLIB error", z_err ); xmlIOErr(XML_IO_WRITE, (const char *) msg); return ( -1 ); } } buff->crc = crc32( buff->crc, (unsigned char *)src, len ); return ( len ); } /** * xmlZMemBuffGetContent * @buff: Compressed memory content buffer * @data_ref: Pointer reference to point to compressed content * * Flushes the compression buffers, appends gzip file trailers and * returns the compressed content and length of the compressed data. * NOTE: The gzip trailer code here is plagiarized from zlib source. * * Returns the length of the compressed data or -1 on error. */ static int xmlZMemBuffGetContent( xmlZMemBuffPtr buff, char ** data_ref ) { int zlgth = -1; int z_err; if ( ( buff == NULL ) || ( data_ref == NULL ) ) return ( -1 ); /* Need to loop until compression output buffers are flushed */ do { z_err = deflate( &buff->zctrl, Z_FINISH ); if ( z_err == Z_OK ) { /* In this case Z_OK means more buffer space needed */ if ( xmlZMemBuffExtend( buff, buff->size ) == -1 ) return ( -1 ); } } while ( z_err == Z_OK ); /* If the compression state is not Z_STREAM_END, some error occurred */ if ( z_err == Z_STREAM_END ) { /* Need to append the gzip data trailer */ if ( buff->zctrl.avail_out < ( 2 * sizeof( unsigned long ) ) ) { if ( xmlZMemBuffExtend(buff, (2 * sizeof(unsigned long))) == -1 ) return ( -1 ); } /* ** For whatever reason, the CRC and length data are pushed out ** in reverse byte order. So a memcpy can't be used here. */ append_reverse_ulong( buff, buff->crc ); append_reverse_ulong( buff, buff->zctrl.total_in ); zlgth = buff->zctrl.next_out - buff->zbuff; *data_ref = (char *)buff->zbuff; } else { xmlChar msg[500]; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlZMemBuffGetContent: %s - %d\n", "Error flushing zlib buffers. Error code", z_err ); xmlIOErr(XML_IO_WRITE, (const char *) msg); } return ( zlgth ); } #endif /* LIBXML_OUTPUT_ENABLED */ #endif /* HAVE_ZLIB_H */ #ifdef LIBXML_OUTPUT_ENABLED /** * xmlFreeHTTPWriteCtxt * @ctxt: Context to cleanup * * Free allocated memory and reclaim system resources. * * No return value. */ static void xmlFreeHTTPWriteCtxt( xmlIOHTTPWriteCtxtPtr ctxt ) { if ( ctxt->uri != NULL ) xmlFree( ctxt->uri ); if ( ctxt->doc_buff != NULL ) { #ifdef HAVE_ZLIB_H if ( ctxt->compression > 0 ) { xmlFreeZMemBuff( ctxt->doc_buff ); } else #endif { xmlOutputBufferClose( ctxt->doc_buff ); } } xmlFree( ctxt ); return; } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlIOHTTPMatch: * @filename: the URI for matching * * check if the URI matches an HTTP one * * Returns 1 if matches, 0 otherwise */ int xmlIOHTTPMatch (const char *filename) { if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "http://", 7)) return(1); return(0); } /** * xmlIOHTTPOpen: * @filename: the URI for matching * * open an HTTP I/O channel * * Returns an I/O context or NULL in case of error */ void * xmlIOHTTPOpen (const char *filename) { return(xmlNanoHTTPOpen(filename, NULL)); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlIOHTTPOpenW: * @post_uri: The destination URI for the document * @compression: The compression desired for the document. * * Open a temporary buffer to collect the document for a subsequent HTTP POST * request. Non-static as is called from the output buffer creation routine. * * Returns an I/O context or NULL in case of error. */ void * xmlIOHTTPOpenW(const char *post_uri, int compression) { xmlIOHTTPWriteCtxtPtr ctxt = NULL; if (post_uri == NULL) return (NULL); ctxt = xmlMalloc(sizeof(xmlIOHTTPWriteCtxt)); if (ctxt == NULL) { xmlIOErrMemory("creating HTTP output context"); return (NULL); } (void) memset(ctxt, 0, sizeof(xmlIOHTTPWriteCtxt)); ctxt->uri = (char *) xmlStrdup((const xmlChar *)post_uri); if (ctxt->uri == NULL) { xmlIOErrMemory("copying URI"); xmlFreeHTTPWriteCtxt(ctxt); return (NULL); } /* * ** Since the document length is required for an HTTP post, * ** need to put the document into a buffer. A memory buffer * ** is being used to avoid pushing the data to disk and back. */ #ifdef HAVE_ZLIB_H if ((compression > 0) && (compression <= 9)) { ctxt->compression = compression; ctxt->doc_buff = xmlCreateZMemBuff(compression); } else #endif { /* Any character conversions should have been done before this */ ctxt->doc_buff = xmlAllocOutputBuffer(NULL); } if (ctxt->doc_buff == NULL) { xmlFreeHTTPWriteCtxt(ctxt); ctxt = NULL; } return (ctxt); } #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_OUTPUT_ENABLED /** * xmlIOHTTPDfltOpenW * @post_uri: The destination URI for this document. * * Calls xmlIOHTTPOpenW with no compression to set up for a subsequent * HTTP post command. This function should generally not be used as * the open callback is short circuited in xmlOutputBufferCreateFile. * * Returns a pointer to the new IO context. */ static void * xmlIOHTTPDfltOpenW( const char * post_uri ) { return ( xmlIOHTTPOpenW( post_uri, 0 ) ); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlIOHTTPRead: * @context: the I/O context * @buffer: where to drop data * @len: number of bytes to write * * Read @len bytes to @buffer from the I/O channel. * * Returns the number of bytes written */ int xmlIOHTTPRead(void * context, char * buffer, int len) { if ((buffer == NULL) || (len < 0)) return(-1); return(xmlNanoHTTPRead(context, &buffer[0], len)); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlIOHTTPWrite * @context: previously opened writing context * @buffer: data to output to temporary buffer * @len: bytes to output * * Collect data from memory buffer into a temporary file for later * processing. * * Returns number of bytes written. */ static int xmlIOHTTPWrite( void * context, const char * buffer, int len ) { xmlIOHTTPWriteCtxtPtr ctxt = context; if ( ( ctxt == NULL ) || ( ctxt->doc_buff == NULL ) || ( buffer == NULL ) ) return ( -1 ); if ( len > 0 ) { /* Use gzwrite or fwrite as previously setup in the open call */ #ifdef HAVE_ZLIB_H if ( ctxt->compression > 0 ) len = xmlZMemBuffAppend( ctxt->doc_buff, buffer, len ); else #endif len = xmlOutputBufferWrite( ctxt->doc_buff, len, buffer ); if ( len < 0 ) { xmlChar msg[500]; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlIOHTTPWrite: %s\n%s '%s'.\n", "Error appending to internal buffer.", "Error sending document to URI", ctxt->uri ); xmlIOErr(XML_IO_WRITE, (const char *) msg); } } return ( len ); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlIOHTTPClose: * @context: the I/O context * * Close an HTTP I/O channel * * Returns 0 */ int xmlIOHTTPClose (void * context) { xmlNanoHTTPClose(context); return 0; } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlIOHTTCloseWrite * @context: The I/O context * @http_mthd: The HTTP method to be used when sending the data * * Close the transmit HTTP I/O channel and actually send the data. */ static int xmlIOHTTPCloseWrite( void * context, const char * http_mthd ) { int close_rc = -1; int http_rtn = 0; int content_lgth = 0; xmlIOHTTPWriteCtxtPtr ctxt = context; char * http_content = NULL; char * content_encoding = NULL; char * content_type = (char *) "text/xml"; void * http_ctxt = NULL; if ( ( ctxt == NULL ) || ( http_mthd == NULL ) ) return ( -1 ); /* Retrieve the content from the appropriate buffer */ #ifdef HAVE_ZLIB_H if ( ctxt->compression > 0 ) { content_lgth = xmlZMemBuffGetContent( ctxt->doc_buff, &http_content ); content_encoding = (char *) "Content-Encoding: gzip"; } else #endif { /* Pull the data out of the memory output buffer */ xmlOutputBufferPtr dctxt = ctxt->doc_buff; http_content = (char *)dctxt->buffer->content; content_lgth = dctxt->buffer->use; } if ( http_content == NULL ) { xmlChar msg[500]; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlIOHTTPCloseWrite: %s '%s' %s '%s'.\n", "Error retrieving content.\nUnable to", http_mthd, "data to URI", ctxt->uri ); xmlIOErr(XML_IO_WRITE, (const char *) msg); } else { http_ctxt = xmlNanoHTTPMethod( ctxt->uri, http_mthd, http_content, &content_type, content_encoding, content_lgth ); if ( http_ctxt != NULL ) { #ifdef DEBUG_HTTP /* If testing/debugging - dump reply with request content */ FILE * tst_file = NULL; char buffer[ 4096 ]; char * dump_name = NULL; int avail; xmlGenericError( xmlGenericErrorContext, "xmlNanoHTTPCloseWrite: HTTP %s to\n%s returned %d.\n", http_mthd, ctxt->uri, xmlNanoHTTPReturnCode( http_ctxt ) ); /* ** Since either content or reply may be gzipped, ** dump them to separate files instead of the ** standard error context. */ dump_name = tempnam( NULL, "lxml" ); if ( dump_name != NULL ) { (void)snprintf( buffer, sizeof(buffer), "%s.content", dump_name ); tst_file = fopen( buffer, "wb" ); if ( tst_file != NULL ) { xmlGenericError( xmlGenericErrorContext, "Transmitted content saved in file: %s\n", buffer ); fwrite( http_content, sizeof( char ), content_lgth, tst_file ); fclose( tst_file ); } (void)snprintf( buffer, sizeof(buffer), "%s.reply", dump_name ); tst_file = fopen( buffer, "wb" ); if ( tst_file != NULL ) { xmlGenericError( xmlGenericErrorContext, "Reply content saved in file: %s\n", buffer ); while ( (avail = xmlNanoHTTPRead( http_ctxt, buffer, sizeof( buffer ) )) > 0 ) { fwrite( buffer, sizeof( char ), avail, tst_file ); } fclose( tst_file ); } free( dump_name ); } #endif /* DEBUG_HTTP */ http_rtn = xmlNanoHTTPReturnCode( http_ctxt ); if ( ( http_rtn >= 200 ) && ( http_rtn < 300 ) ) close_rc = 0; else { xmlChar msg[500]; xmlStrPrintf(msg, 500, (const xmlChar *) "xmlIOHTTPCloseWrite: HTTP '%s' of %d %s\n'%s' %s %d\n", http_mthd, content_lgth, "bytes to URI", ctxt->uri, "failed. HTTP return code:", http_rtn ); xmlIOErr(XML_IO_WRITE, (const char *) msg); } xmlNanoHTTPClose( http_ctxt ); xmlFree( content_type ); } } /* Final cleanups */ xmlFreeHTTPWriteCtxt( ctxt ); return ( close_rc ); } /** * xmlIOHTTPClosePut * * @context: The I/O context * * Close the transmit HTTP I/O channel and actually send data using a PUT * HTTP method. */ static int xmlIOHTTPClosePut( void * ctxt ) { return ( xmlIOHTTPCloseWrite( ctxt, "PUT" ) ); } /** * xmlIOHTTPClosePost * * @context: The I/O context * * Close the transmit HTTP I/O channel and actually send data using a POST * HTTP method. */ static int xmlIOHTTPClosePost( void * ctxt ) { return ( xmlIOHTTPCloseWrite( ctxt, "POST" ) ); } #endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_HTTP_ENABLED */ #ifdef LIBXML_FTP_ENABLED /************************************************************************ * * * I/O for FTP file accesses * * * ************************************************************************/ /** * xmlIOFTPMatch: * @filename: the URI for matching * * check if the URI matches an FTP one * * Returns 1 if matches, 0 otherwise */ int xmlIOFTPMatch (const char *filename) { if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "ftp://", 6)) return(1); return(0); } /** * xmlIOFTPOpen: * @filename: the URI for matching * * open an FTP I/O channel * * Returns an I/O context or NULL in case of error */ void * xmlIOFTPOpen (const char *filename) { return(xmlNanoFTPOpen(filename)); } /** * xmlIOFTPRead: * @context: the I/O context * @buffer: where to drop data * @len: number of bytes to write * * Read @len bytes to @buffer from the I/O channel. * * Returns the number of bytes written */ int xmlIOFTPRead(void * context, char * buffer, int len) { if ((buffer == NULL) || (len < 0)) return(-1); return(xmlNanoFTPRead(context, &buffer[0], len)); } /** * xmlIOFTPClose: * @context: the I/O context * * Close an FTP I/O channel * * Returns 0 */ int xmlIOFTPClose (void * context) { return ( xmlNanoFTPClose(context) ); } #endif /* LIBXML_FTP_ENABLED */ /** * xmlRegisterInputCallbacks: * @matchFunc: the xmlInputMatchCallback * @openFunc: the xmlInputOpenCallback * @readFunc: the xmlInputReadCallback * @closeFunc: the xmlInputCloseCallback * * Register a new set of I/O callback for handling parser input. * * Returns the registered handler number or -1 in case of error */ int xmlRegisterInputCallbacks(xmlInputMatchCallback matchFunc, xmlInputOpenCallback openFunc, xmlInputReadCallback readFunc, xmlInputCloseCallback closeFunc) { if (xmlInputCallbackNr >= MAX_INPUT_CALLBACK) { return(-1); } xmlInputCallbackTable[xmlInputCallbackNr].matchcallback = matchFunc; xmlInputCallbackTable[xmlInputCallbackNr].opencallback = openFunc; xmlInputCallbackTable[xmlInputCallbackNr].readcallback = readFunc; xmlInputCallbackTable[xmlInputCallbackNr].closecallback = closeFunc; xmlInputCallbackInitialized = 1; return(xmlInputCallbackNr++); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlRegisterOutputCallbacks: * @matchFunc: the xmlOutputMatchCallback * @openFunc: the xmlOutputOpenCallback * @writeFunc: the xmlOutputWriteCallback * @closeFunc: the xmlOutputCloseCallback * * Register a new set of I/O callback for handling output. * * Returns the registered handler number or -1 in case of error */ int xmlRegisterOutputCallbacks(xmlOutputMatchCallback matchFunc, xmlOutputOpenCallback openFunc, xmlOutputWriteCallback writeFunc, xmlOutputCloseCallback closeFunc) { if (xmlOutputCallbackNr >= MAX_INPUT_CALLBACK) { return(-1); } xmlOutputCallbackTable[xmlOutputCallbackNr].matchcallback = matchFunc; xmlOutputCallbackTable[xmlOutputCallbackNr].opencallback = openFunc; xmlOutputCallbackTable[xmlOutputCallbackNr].writecallback = writeFunc; xmlOutputCallbackTable[xmlOutputCallbackNr].closecallback = closeFunc; xmlOutputCallbackInitialized = 1; return(xmlOutputCallbackNr++); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlRegisterDefaultInputCallbacks: * * Registers the default compiled-in I/O handlers. */ void xmlRegisterDefaultInputCallbacks(void) { if (xmlInputCallbackInitialized) return; #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) xmlInitPlatformSpecificIo(); #endif xmlRegisterInputCallbacks(xmlFileMatch, xmlFileOpen, xmlFileRead, xmlFileClose); #ifdef HAVE_ZLIB_H xmlRegisterInputCallbacks(xmlGzfileMatch, xmlGzfileOpen, xmlGzfileRead, xmlGzfileClose); #endif /* HAVE_ZLIB_H */ #ifdef LIBXML_HTTP_ENABLED xmlRegisterInputCallbacks(xmlIOHTTPMatch, xmlIOHTTPOpen, xmlIOHTTPRead, xmlIOHTTPClose); #endif /* LIBXML_HTTP_ENABLED */ #ifdef LIBXML_FTP_ENABLED xmlRegisterInputCallbacks(xmlIOFTPMatch, xmlIOFTPOpen, xmlIOFTPRead, xmlIOFTPClose); #endif /* LIBXML_FTP_ENABLED */ xmlInputCallbackInitialized = 1; } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlRegisterDefaultOutputCallbacks: * * Registers the default compiled-in I/O handlers. */ void xmlRegisterDefaultOutputCallbacks (void) { if (xmlOutputCallbackInitialized) return; #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) xmlInitPlatformSpecificIo(); #endif xmlRegisterOutputCallbacks(xmlFileMatch, xmlFileOpenW, xmlFileWrite, xmlFileClose); #ifdef LIBXML_HTTP_ENABLED xmlRegisterOutputCallbacks(xmlIOHTTPMatch, xmlIOHTTPDfltOpenW, xmlIOHTTPWrite, xmlIOHTTPClosePut); #endif /********************************* No way a-priori to distinguish between gzipped files from uncompressed ones except opening if existing then closing and saving with same compression ratio ... a pain. #ifdef HAVE_ZLIB_H xmlRegisterOutputCallbacks(xmlGzfileMatch, xmlGzfileOpen, xmlGzfileWrite, xmlGzfileClose); #endif Nor FTP PUT .... #ifdef LIBXML_FTP_ENABLED xmlRegisterOutputCallbacks(xmlIOFTPMatch, xmlIOFTPOpen, xmlIOFTPWrite, xmlIOFTPClose); #endif **********************************/ xmlOutputCallbackInitialized = 1; } #ifdef LIBXML_HTTP_ENABLED /** * xmlRegisterHTTPPostCallbacks: * * By default, libxml submits HTTP output requests using the "PUT" method. * Calling this method changes the HTTP output method to use the "POST" * method instead. * */ void xmlRegisterHTTPPostCallbacks( void ) { /* Register defaults if not done previously */ if ( xmlOutputCallbackInitialized == 0 ) xmlRegisterDefaultOutputCallbacks( ); xmlRegisterOutputCallbacks(xmlIOHTTPMatch, xmlIOHTTPDfltOpenW, xmlIOHTTPWrite, xmlIOHTTPClosePost); return; } #endif #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlAllocParserInputBuffer: * @enc: the charset encoding if known * * Create a buffered parser input for progressive parsing * * Returns the new parser input or NULL */ xmlParserInputBufferPtr xmlAllocParserInputBuffer(xmlCharEncoding enc) { xmlParserInputBufferPtr ret; ret = (xmlParserInputBufferPtr) xmlMalloc(sizeof(xmlParserInputBuffer)); if (ret == NULL) { xmlIOErrMemory("creating input buffer"); return(NULL); } memset(ret, 0, (size_t) sizeof(xmlParserInputBuffer)); ret->buffer = xmlBufferCreateSize(2 * xmlDefaultBufferSize); if (ret->buffer == NULL) { xmlFree(ret); return(NULL); } ret->buffer->alloc = XML_BUFFER_ALLOC_DOUBLEIT; ret->encoder = xmlGetCharEncodingHandler(enc); if (ret->encoder != NULL) ret->raw = xmlBufferCreateSize(2 * xmlDefaultBufferSize); else ret->raw = NULL; ret->readcallback = NULL; ret->closecallback = NULL; ret->context = NULL; ret->compressed = -1; ret->rawconsumed = 0; return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlAllocOutputBuffer: * @encoder: the encoding converter or NULL * * Create a buffered parser output * * Returns the new parser output or NULL */ xmlOutputBufferPtr xmlAllocOutputBuffer(xmlCharEncodingHandlerPtr encoder) { xmlOutputBufferPtr ret; ret = (xmlOutputBufferPtr) xmlMalloc(sizeof(xmlOutputBuffer)); if (ret == NULL) { xmlIOErrMemory("creating output buffer"); return(NULL); } memset(ret, 0, (size_t) sizeof(xmlOutputBuffer)); ret->buffer = xmlBufferCreate(); if (ret->buffer == NULL) { xmlFree(ret); return(NULL); } ret->buffer->alloc = XML_BUFFER_ALLOC_DOUBLEIT; ret->encoder = encoder; if (encoder != NULL) { ret->conv = xmlBufferCreateSize(4000); /* * This call is designed to initiate the encoder state */ xmlCharEncOutFunc(encoder, ret->conv, NULL); } else ret->conv = NULL; ret->writecallback = NULL; ret->closecallback = NULL; ret->context = NULL; ret->written = 0; return(ret); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlFreeParserInputBuffer: * @in: a buffered parser input * * Free up the memory used by a buffered parser input */ void xmlFreeParserInputBuffer(xmlParserInputBufferPtr in) { if (in == NULL) return; if (in->raw) { xmlBufferFree(in->raw); in->raw = NULL; } if (in->encoder != NULL) { xmlCharEncCloseFunc(in->encoder); } if (in->closecallback != NULL) { in->closecallback(in->context); } if (in->buffer != NULL) { xmlBufferFree(in->buffer); in->buffer = NULL; } xmlFree(in); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlOutputBufferClose: * @out: a buffered output * * flushes and close the output I/O channel * and free up all the associated resources * * Returns the number of byte written or -1 in case of error. */ int xmlOutputBufferClose(xmlOutputBufferPtr out) { int written; int err_rc = 0; if (out == NULL) return (-1); if (out->writecallback != NULL) xmlOutputBufferFlush(out); if (out->closecallback != NULL) { err_rc = out->closecallback(out->context); } written = out->written; if (out->conv) { xmlBufferFree(out->conv); out->conv = NULL; } if (out->encoder != NULL) { xmlCharEncCloseFunc(out->encoder); } if (out->buffer != NULL) { xmlBufferFree(out->buffer); out->buffer = NULL; } if (out->error) err_rc = -1; xmlFree(out); return ((err_rc == 0) ? written : err_rc); } #endif /* LIBXML_OUTPUT_ENABLED */ xmlParserInputBufferPtr __xmlParserInputBufferCreateFilename(const char *URI, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; int i = 0; void *context = NULL; if (xmlInputCallbackInitialized == 0) xmlRegisterDefaultInputCallbacks(); if (URI == NULL) return(NULL); /* * Try to find one of the input accept method accepting that scheme * Go in reverse to give precedence to user defined handlers. */ if (context == NULL) { for (i = xmlInputCallbackNr - 1;i >= 0;i--) { if ((xmlInputCallbackTable[i].matchcallback != NULL) && (xmlInputCallbackTable[i].matchcallback(URI) != 0)) { context = xmlInputCallbackTable[i].opencallback(URI); if (context != NULL) { break; } } } } if (context == NULL) { return(NULL); } /* * Allocate the Input buffer front-end. */ ret = xmlAllocParserInputBuffer(enc); if (ret != NULL) { ret->context = context; ret->readcallback = xmlInputCallbackTable[i].readcallback; ret->closecallback = xmlInputCallbackTable[i].closecallback; #ifdef HAVE_ZLIB_H if ((xmlInputCallbackTable[i].opencallback == xmlGzfileOpen) && (strcmp(URI, "-") != 0)) { if (((z_stream *)context)->avail_in > 4) { char *cptr, buff4[4]; cptr = (char *) ((z_stream *)context)->next_in; if (gzread(context, buff4, 4) == 4) { if (strncmp(buff4, cptr, 4) == 0) ret->compressed = 0; else ret->compressed = 1; gzrewind(context); } } } #endif } else xmlInputCallbackTable[i].closecallback (context); return(ret); } /** * xmlParserInputBufferCreateFilename: * @URI: a C string containing the URI or filename * @enc: the charset encoding if known * * Create a buffered parser input for the progressive parsing of a file * If filename is "-' then we use stdin as the input. * Automatic support for ZLIB/Compress compressed document is provided * by default if found at compile-time. * Do an encoding check if enc == XML_CHAR_ENCODING_NONE * * Returns the new parser input or NULL */ xmlParserInputBufferPtr xmlParserInputBufferCreateFilename(const char *URI, xmlCharEncoding enc) { if ((xmlParserInputBufferCreateFilenameValue)) { return xmlParserInputBufferCreateFilenameValue(URI, enc); } return __xmlParserInputBufferCreateFilename(URI, enc); } #ifdef LIBXML_OUTPUT_ENABLED xmlOutputBufferPtr __xmlOutputBufferCreateFilename(const char *URI, xmlCharEncodingHandlerPtr encoder, int compression ATTRIBUTE_UNUSED) { xmlOutputBufferPtr ret; xmlURIPtr puri; int i = 0; void *context = NULL; char *unescaped = NULL; #ifdef HAVE_ZLIB_H int is_file_uri = 1; #endif if (xmlOutputCallbackInitialized == 0) xmlRegisterDefaultOutputCallbacks(); if (URI == NULL) return(NULL); puri = xmlParseURI(URI); if (puri != NULL) { #ifdef HAVE_ZLIB_H if ((puri->scheme != NULL) && (!xmlStrEqual(BAD_CAST puri->scheme, BAD_CAST "file"))) is_file_uri = 0; #endif /* * try to limit the damages of the URI unescaping code. */ if ((puri->scheme == NULL) || (xmlStrEqual(BAD_CAST puri->scheme, BAD_CAST "file"))) unescaped = xmlURIUnescapeString(URI, 0, NULL); xmlFreeURI(puri); } /* * Try to find one of the output accept method accepting that scheme * Go in reverse to give precedence to user defined handlers. * try with an unescaped version of the URI */ if (unescaped != NULL) { #ifdef HAVE_ZLIB_H if ((compression > 0) && (compression <= 9) && (is_file_uri == 1)) { context = xmlGzfileOpenW(unescaped, compression); if (context != NULL) { ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = context; ret->writecallback = xmlGzfileWrite; ret->closecallback = xmlGzfileClose; } xmlFree(unescaped); return(ret); } } #endif for (i = xmlOutputCallbackNr - 1;i >= 0;i--) { if ((xmlOutputCallbackTable[i].matchcallback != NULL) && (xmlOutputCallbackTable[i].matchcallback(unescaped) != 0)) { #if defined(LIBXML_HTTP_ENABLED) && defined(HAVE_ZLIB_H) /* Need to pass compression parameter into HTTP open calls */ if (xmlOutputCallbackTable[i].matchcallback == xmlIOHTTPMatch) context = xmlIOHTTPOpenW(unescaped, compression); else #endif context = xmlOutputCallbackTable[i].opencallback(unescaped); if (context != NULL) break; } } xmlFree(unescaped); } /* * If this failed try with a non-escaped URI this may be a strange * filename */ if (context == NULL) { #ifdef HAVE_ZLIB_H if ((compression > 0) && (compression <= 9) && (is_file_uri == 1)) { context = xmlGzfileOpenW(URI, compression); if (context != NULL) { ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = context; ret->writecallback = xmlGzfileWrite; ret->closecallback = xmlGzfileClose; } return(ret); } } #endif for (i = xmlOutputCallbackNr - 1;i >= 0;i--) { if ((xmlOutputCallbackTable[i].matchcallback != NULL) && (xmlOutputCallbackTable[i].matchcallback(URI) != 0)) { #if defined(LIBXML_HTTP_ENABLED) && defined(HAVE_ZLIB_H) /* Need to pass compression parameter into HTTP open calls */ if (xmlOutputCallbackTable[i].matchcallback == xmlIOHTTPMatch) context = xmlIOHTTPOpenW(URI, compression); else #endif context = xmlOutputCallbackTable[i].opencallback(URI); if (context != NULL) break; } } } if (context == NULL) { return(NULL); } /* * Allocate the Output buffer front-end. */ ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = context; ret->writecallback = xmlOutputCallbackTable[i].writecallback; ret->closecallback = xmlOutputCallbackTable[i].closecallback; } return(ret); } /** * xmlOutputBufferCreateFilename: * @URI: a C string containing the URI or filename * @encoder: the encoding converter or NULL * @compression: the compression ration (0 none, 9 max). * * Create a buffered output for the progressive saving of a file * If filename is "-' then we use stdout as the output. * Automatic support for ZLIB/Compress compressed document is provided * by default if found at compile-time. * TODO: currently if compression is set, the library only support * writing to a local file. * * Returns the new output or NULL */ xmlOutputBufferPtr xmlOutputBufferCreateFilename(const char *URI, xmlCharEncodingHandlerPtr encoder, int compression ATTRIBUTE_UNUSED) { if ((xmlOutputBufferCreateFilenameValue)) { return xmlOutputBufferCreateFilenameValue(URI, encoder, compression); } return __xmlOutputBufferCreateFilename(URI, encoder, compression); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlParserInputBufferCreateFile: * @file: a FILE* * @enc: the charset encoding if known * * Create a buffered parser input for the progressive parsing of a FILE * * buffered C I/O * * Returns the new parser input or NULL */ xmlParserInputBufferPtr xmlParserInputBufferCreateFile(FILE *file, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; if (xmlInputCallbackInitialized == 0) xmlRegisterDefaultInputCallbacks(); if (file == NULL) return(NULL); ret = xmlAllocParserInputBuffer(enc); if (ret != NULL) { ret->context = file; ret->readcallback = xmlFileRead; ret->closecallback = xmlFileFlush; } return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlOutputBufferCreateFile: * @file: a FILE* * @encoder: the encoding converter or NULL * * Create a buffered output for the progressive saving to a FILE * * buffered C I/O * * Returns the new parser output or NULL */ xmlOutputBufferPtr xmlOutputBufferCreateFile(FILE *file, xmlCharEncodingHandlerPtr encoder) { xmlOutputBufferPtr ret; if (xmlOutputCallbackInitialized == 0) xmlRegisterDefaultOutputCallbacks(); if (file == NULL) return(NULL); ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = file; ret->writecallback = xmlFileWrite; ret->closecallback = xmlFileFlush; } return(ret); } /** * xmlOutputBufferCreateBuffer: * @buffer: a xmlBufferPtr * @encoder: the encoding converter or NULL * * Create a buffered output for the progressive saving to a xmlBuffer * * Returns the new parser output or NULL */ xmlOutputBufferPtr xmlOutputBufferCreateBuffer(xmlBufferPtr buffer, xmlCharEncodingHandlerPtr encoder) { xmlOutputBufferPtr ret; if (buffer == NULL) return(NULL); ret = xmlOutputBufferCreateIO((xmlOutputWriteCallback) xmlBufferWrite, (xmlOutputCloseCallback) NULL, (void *) buffer, encoder); return(ret); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlParserInputBufferCreateFd: * @fd: a file descriptor number * @enc: the charset encoding if known * * Create a buffered parser input for the progressive parsing for the input * from a file descriptor * * Returns the new parser input or NULL */ xmlParserInputBufferPtr xmlParserInputBufferCreateFd(int fd, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; if (fd < 0) return(NULL); ret = xmlAllocParserInputBuffer(enc); if (ret != NULL) { ret->context = (void *) (long) fd; ret->readcallback = xmlFdRead; ret->closecallback = xmlFdClose; } return(ret); } /** * xmlParserInputBufferCreateMem: * @mem: the memory input * @size: the length of the memory block * @enc: the charset encoding if known * * Create a buffered parser input for the progressive parsing for the input * from a memory area. * * Returns the new parser input or NULL */ xmlParserInputBufferPtr xmlParserInputBufferCreateMem(const char *mem, int size, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; int errcode; if (size <= 0) return(NULL); if (mem == NULL) return(NULL); ret = xmlAllocParserInputBuffer(enc); if (ret != NULL) { ret->context = (void *) mem; ret->readcallback = (xmlInputReadCallback) xmlNop; ret->closecallback = NULL; errcode = xmlBufferAdd(ret->buffer, (const xmlChar *) mem, size); if (errcode != 0) { xmlFree(ret); return(NULL); } } return(ret); } /** * xmlParserInputBufferCreateStatic: * @mem: the memory input * @size: the length of the memory block * @enc: the charset encoding if known * * Create a buffered parser input for the progressive parsing for the input * from an immutable memory area. This will not copy the memory area to * the buffer, but the memory is expected to be available until the end of * the parsing, this is useful for example when using mmap'ed file. * * Returns the new parser input or NULL */ xmlParserInputBufferPtr xmlParserInputBufferCreateStatic(const char *mem, int size, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; if (size <= 0) return(NULL); if (mem == NULL) return(NULL); ret = (xmlParserInputBufferPtr) xmlMalloc(sizeof(xmlParserInputBuffer)); if (ret == NULL) { xmlIOErrMemory("creating input buffer"); return(NULL); } memset(ret, 0, (size_t) sizeof(xmlParserInputBuffer)); ret->buffer = xmlBufferCreateStatic((void *)mem, (size_t) size); if (ret->buffer == NULL) { xmlFree(ret); return(NULL); } ret->encoder = xmlGetCharEncodingHandler(enc); if (ret->encoder != NULL) ret->raw = xmlBufferCreateSize(2 * xmlDefaultBufferSize); else ret->raw = NULL; ret->compressed = -1; ret->context = (void *) mem; ret->readcallback = NULL; ret->closecallback = NULL; return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlOutputBufferCreateFd: * @fd: a file descriptor number * @encoder: the encoding converter or NULL * * Create a buffered output for the progressive saving * to a file descriptor * * Returns the new parser output or NULL */ xmlOutputBufferPtr xmlOutputBufferCreateFd(int fd, xmlCharEncodingHandlerPtr encoder) { xmlOutputBufferPtr ret; if (fd < 0) return(NULL); ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = (void *) (long) fd; ret->writecallback = xmlFdWrite; ret->closecallback = NULL; } return(ret); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlParserInputBufferCreateIO: * @ioread: an I/O read function * @ioclose: an I/O close function * @ioctx: an I/O handler * @enc: the charset encoding if known * * Create a buffered parser input for the progressive parsing for the input * from an I/O handler * * Returns the new parser input or NULL */ xmlParserInputBufferPtr xmlParserInputBufferCreateIO(xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; if (ioread == NULL) return(NULL); ret = xmlAllocParserInputBuffer(enc); if (ret != NULL) { ret->context = (void *) ioctx; ret->readcallback = ioread; ret->closecallback = ioclose; } return(ret); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlOutputBufferCreateIO: * @iowrite: an I/O write function * @ioclose: an I/O close function * @ioctx: an I/O handler * @encoder: the charset encoding if known * * Create a buffered output for the progressive saving * to an I/O handler * * Returns the new parser output or NULL */ xmlOutputBufferPtr xmlOutputBufferCreateIO(xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose, void *ioctx, xmlCharEncodingHandlerPtr encoder) { xmlOutputBufferPtr ret; if (iowrite == NULL) return(NULL); ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = (void *) ioctx; ret->writecallback = iowrite; ret->closecallback = ioclose; } return(ret); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlParserInputBufferCreateFilenameDefault: * @func: function pointer to the new ParserInputBufferCreateFilenameFunc * * Registers a callback for URI input file handling * * Returns the old value of the registration function */ xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameDefault(xmlParserInputBufferCreateFilenameFunc func) { xmlParserInputBufferCreateFilenameFunc old = xmlParserInputBufferCreateFilenameValue; if (old == NULL) { old = __xmlParserInputBufferCreateFilename; } xmlParserInputBufferCreateFilenameValue = func; return(old); } /** * xmlOutputBufferCreateFilenameDefault: * @func: function pointer to the new OutputBufferCreateFilenameFunc * * Registers a callback for URI output file handling * * Returns the old value of the registration function */ xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func) { xmlOutputBufferCreateFilenameFunc old = xmlOutputBufferCreateFilenameValue; #ifdef LIBXML_OUTPUT_ENABLED if (old == NULL) { old = __xmlOutputBufferCreateFilename; } #endif xmlOutputBufferCreateFilenameValue = func; return(old); } /** * xmlParserInputBufferPush: * @in: a buffered parser input * @len: the size in bytes of the array. * @buf: an char array * * Push the content of the arry in the input buffer * This routine handle the I18N transcoding to internal UTF-8 * This is used when operating the parser in progressive (push) mode. * * Returns the number of chars read and stored in the buffer, or -1 * in case of error. */ int xmlParserInputBufferPush(xmlParserInputBufferPtr in, int len, const char *buf) { int nbchars = 0; int ret; if (len < 0) return(0); if ((in == NULL) || (in->error)) return(-1); if (in->encoder != NULL) { unsigned int use; /* * Store the data in the incoming raw buffer */ if (in->raw == NULL) { in->raw = xmlBufferCreate(); } ret = xmlBufferAdd(in->raw, (const xmlChar *) buf, len); if (ret != 0) return(-1); /* * convert as much as possible to the parser reading buffer. */ use = in->raw->use; nbchars = xmlCharEncInFunc(in->encoder, in->buffer, in->raw); if (nbchars < 0) { xmlIOErr(XML_IO_ENCODER, NULL); in->error = XML_IO_ENCODER; return(-1); } in->rawconsumed += (use - in->raw->use); } else { nbchars = len; ret = xmlBufferAdd(in->buffer, (xmlChar *) buf, nbchars); if (ret != 0) return(-1); } #ifdef DEBUG_INPUT xmlGenericError(xmlGenericErrorContext, "I/O: pushed %d chars, buffer %d/%d\n", nbchars, in->buffer->use, in->buffer->size); #endif return(nbchars); } /** * endOfInput: * * When reading from an Input channel indicated end of file or error * don't reread from it again. */ static int endOfInput (void * context ATTRIBUTE_UNUSED, char * buffer ATTRIBUTE_UNUSED, int len ATTRIBUTE_UNUSED) { return(0); } /** * xmlParserInputBufferGrow: * @in: a buffered parser input * @len: indicative value of the amount of chars to read * * Grow up the content of the input buffer, the old data are preserved * This routine handle the I18N transcoding to internal UTF-8 * This routine is used when operating the parser in normal (pull) mode * * TODO: one should be able to remove one extra copy by copying directly * onto in->buffer or in->raw * * Returns the number of chars read and stored in the buffer, or -1 * in case of error. */ int xmlParserInputBufferGrow(xmlParserInputBufferPtr in, int len) { char *buffer = NULL; int res = 0; int nbchars = 0; int buffree; unsigned int needSize; if ((in == NULL) || (in->error)) return(-1); if ((len <= MINLEN) && (len != 4)) len = MINLEN; buffree = in->buffer->size - in->buffer->use; if (buffree <= 0) { xmlIOErr(XML_IO_BUFFER_FULL, NULL); in->error = XML_IO_BUFFER_FULL; return(-1); } needSize = in->buffer->use + len + 1; if (needSize > in->buffer->size){ if (!xmlBufferResize(in->buffer, needSize)){ xmlIOErrMemory("growing input buffer"); in->error = XML_ERR_NO_MEMORY; return(-1); } } buffer = (char *)&in->buffer->content[in->buffer->use]; /* * Call the read method for this I/O type. */ if (in->readcallback != NULL) { res = in->readcallback(in->context, &buffer[0], len); if (res <= 0) in->readcallback = endOfInput; } else { xmlIOErr(XML_IO_NO_INPUT, NULL); in->error = XML_IO_NO_INPUT; return(-1); } if (res < 0) { return(-1); } len = res; if (in->encoder != NULL) { unsigned int use; /* * Store the data in the incoming raw buffer */ if (in->raw == NULL) { in->raw = xmlBufferCreate(); } res = xmlBufferAdd(in->raw, (const xmlChar *) buffer, len); if (res != 0) return(-1); /* * convert as much as possible to the parser reading buffer. */ use = in->raw->use; nbchars = xmlCharEncInFunc(in->encoder, in->buffer, in->raw); if (nbchars < 0) { xmlIOErr(XML_IO_ENCODER, NULL); in->error = XML_IO_ENCODER; return(-1); } in->rawconsumed += (use - in->raw->use); } else { nbchars = len; in->buffer->use += nbchars; buffer[nbchars] = 0; } #ifdef DEBUG_INPUT xmlGenericError(xmlGenericErrorContext, "I/O: read %d chars, buffer %d/%d\n", nbchars, in->buffer->use, in->buffer->size); #endif return(nbchars); } /** * xmlParserInputBufferRead: * @in: a buffered parser input * @len: indicative value of the amount of chars to read * * Refresh the content of the input buffer, the old data are considered * consumed * This routine handle the I18N transcoding to internal UTF-8 * * Returns the number of chars read and stored in the buffer, or -1 * in case of error. */ int xmlParserInputBufferRead(xmlParserInputBufferPtr in, int len) { if ((in == NULL) || (in->error)) return(-1); if (in->readcallback != NULL) return(xmlParserInputBufferGrow(in, len)); else if ((in->buffer != NULL) && (in->buffer->alloc == XML_BUFFER_ALLOC_IMMUTABLE)) return(0); else return(-1); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlOutputBufferWrite: * @out: a buffered parser output * @len: the size in bytes of the array. * @buf: an char array * * Write the content of the array in the output I/O buffer * This routine handle the I18N transcoding from internal UTF-8 * The buffer is lossless, i.e. will store in case of partial * or delayed writes. * * Returns the number of chars immediately written, or -1 * in case of error. */ int xmlOutputBufferWrite(xmlOutputBufferPtr out, int len, const char *buf) { int nbchars = 0; /* number of chars to output to I/O */ int ret; /* return from function call */ int written = 0; /* number of char written to I/O so far */ int chunk; /* number of byte curreent processed from buf */ if ((out == NULL) || (out->error)) return(-1); if (len < 0) return(0); if (out->error) return(-1); do { chunk = len; if (chunk > 4 * MINLEN) chunk = 4 * MINLEN; /* * first handle encoding stuff. */ if (out->encoder != NULL) { /* * Store the data in the incoming raw buffer */ if (out->conv == NULL) { out->conv = xmlBufferCreate(); } ret = xmlBufferAdd(out->buffer, (const xmlChar *) buf, chunk); if (ret != 0) return(-1); if ((out->buffer->use < MINLEN) && (chunk == len)) goto done; /* * convert as much as possible to the parser reading buffer. */ ret = xmlCharEncOutFunc(out->encoder, out->conv, out->buffer); if ((ret < 0) && (ret != -3)) { xmlIOErr(XML_IO_ENCODER, NULL); out->error = XML_IO_ENCODER; return(-1); } nbchars = out->conv->use; } else { ret = xmlBufferAdd(out->buffer, (const xmlChar *) buf, chunk); if (ret != 0) return(-1); nbchars = out->buffer->use; } buf += chunk; len -= chunk; if ((nbchars < MINLEN) && (len <= 0)) goto done; if (out->writecallback) { /* * second write the stuff to the I/O channel */ if (out->encoder != NULL) { ret = out->writecallback(out->context, (const char *)out->conv->content, nbchars); if (ret >= 0) xmlBufferShrink(out->conv, ret); } else { ret = out->writecallback(out->context, (const char *)out->buffer->content, nbchars); if (ret >= 0) xmlBufferShrink(out->buffer, ret); } if (ret < 0) { xmlIOErr(XML_IO_WRITE, NULL); out->error = XML_IO_WRITE; return(ret); } out->written += ret; } written += nbchars; } while (len > 0); done: #ifdef DEBUG_INPUT xmlGenericError(xmlGenericErrorContext, "I/O: wrote %d chars\n", written); #endif return(written); } /** * xmlEscapeContent: * @out: a pointer to an array of bytes to store the result * @outlen: the length of @out * @in: a pointer to an array of unescaped UTF-8 bytes * @inlen: the length of @in * * Take a block of UTF-8 chars in and escape them. * Returns 0 if success, or -1 otherwise * The value of @inlen after return is the number of octets consumed * if the return value is positive, else unpredictable. * The value of @outlen after return is the number of octets consumed. */ static int xmlEscapeContent(unsigned char* out, int *outlen, const xmlChar* in, int *inlen) { unsigned char* outstart = out; const unsigned char* base = in; unsigned char* outend = out + *outlen; const unsigned char* inend; inend = in + (*inlen); while ((in < inend) && (out < outend)) { if (*in == '<') { if (outend - out < 4) break; *out++ = '&'; *out++ = 'l'; *out++ = 't'; *out++ = ';'; } else if (*in == '>') { if (outend - out < 4) break; *out++ = '&'; *out++ = 'g'; *out++ = 't'; *out++ = ';'; } else if (*in == '&') { if (outend - out < 5) break; *out++ = '&'; *out++ = 'a'; *out++ = 'm'; *out++ = 'p'; *out++ = ';'; } else if (*in == '\r') { if (outend - out < 5) break; *out++ = '&'; *out++ = '#'; *out++ = '1'; *out++ = '3'; *out++ = ';'; } else { *out++ = (unsigned char) *in; } ++in; } *outlen = out - outstart; *inlen = in - base; return(0); } /** * xmlOutputBufferWriteEscape: * @out: a buffered parser output * @str: a zero terminated UTF-8 string * @escaping: an optional escaping function (or NULL) * * Write the content of the string in the output I/O buffer * This routine escapes the caracters and then handle the I18N * transcoding from internal UTF-8 * The buffer is lossless, i.e. will store in case of partial * or delayed writes. * * Returns the number of chars immediately written, or -1 * in case of error. */ int xmlOutputBufferWriteEscape(xmlOutputBufferPtr out, const xmlChar *str, xmlCharEncodingOutputFunc escaping) { int nbchars = 0; /* number of chars to output to I/O */ int ret; /* return from function call */ int written = 0; /* number of char written to I/O so far */ int oldwritten=0;/* loop guard */ int chunk; /* number of byte currently processed from str */ int len; /* number of bytes in str */ int cons; /* byte from str consumed */ if ((out == NULL) || (out->error) || (str == NULL) || (out->buffer == NULL) || (out->buffer->alloc == XML_BUFFER_ALLOC_IMMUTABLE)) return(-1); len = strlen((const char *)str); if (len < 0) return(0); if (out->error) return(-1); if (escaping == NULL) escaping = xmlEscapeContent; do { oldwritten = written; /* * how many bytes to consume and how many bytes to store. */ cons = len; chunk = (out->buffer->size - out->buffer->use) - 1; /* * first handle encoding stuff. */ if (out->encoder != NULL) { /* * Store the data in the incoming raw buffer */ if (out->conv == NULL) { out->conv = xmlBufferCreate(); } ret = escaping(out->buffer->content + out->buffer->use , &chunk, str, &cons); if ((ret < 0) || (chunk == 0)) /* chunk==0 => nothing done */ return(-1); out->buffer->use += chunk; out->buffer->content[out->buffer->use] = 0; if ((out->buffer->use < MINLEN) && (cons == len)) goto done; /* * convert as much as possible to the output buffer. */ ret = xmlCharEncOutFunc(out->encoder, out->conv, out->buffer); if ((ret < 0) && (ret != -3)) { xmlIOErr(XML_IO_ENCODER, NULL); out->error = XML_IO_ENCODER; return(-1); } nbchars = out->conv->use; } else { ret = escaping(out->buffer->content + out->buffer->use , &chunk, str, &cons); if ((ret < 0) || (chunk == 0)) /* chunk==0 => nothing done */ return(-1); out->buffer->use += chunk; out->buffer->content[out->buffer->use] = 0; nbchars = out->buffer->use; } str += cons; len -= cons; if ((nbchars < MINLEN) && (len <= 0)) goto done; if (out->writecallback) { /* * second write the stuff to the I/O channel */ if (out->encoder != NULL) { ret = out->writecallback(out->context, (const char *)out->conv->content, nbchars); if (ret >= 0) xmlBufferShrink(out->conv, ret); } else { ret = out->writecallback(out->context, (const char *)out->buffer->content, nbchars); if (ret >= 0) xmlBufferShrink(out->buffer, ret); } if (ret < 0) { xmlIOErr(XML_IO_WRITE, NULL); out->error = XML_IO_WRITE; return(ret); } out->written += ret; } else if (out->buffer->size - out->buffer->use < MINLEN) { xmlBufferResize(out->buffer, out->buffer->size + MINLEN); } written += nbchars; } while ((len > 0) && (oldwritten != written)); done: #ifdef DEBUG_INPUT xmlGenericError(xmlGenericErrorContext, "I/O: wrote %d chars\n", written); #endif return(written); } /** * xmlOutputBufferWriteString: * @out: a buffered parser output * @str: a zero terminated C string * * Write the content of the string in the output I/O buffer * This routine handle the I18N transcoding from internal UTF-8 * The buffer is lossless, i.e. will store in case of partial * or delayed writes. * * Returns the number of chars immediately written, or -1 * in case of error. */ int xmlOutputBufferWriteString(xmlOutputBufferPtr out, const char *str) { int len; if ((out == NULL) || (out->error)) return(-1); if (str == NULL) return(-1); len = strlen(str); if (len > 0) return(xmlOutputBufferWrite(out, len, str)); return(len); } /** * xmlOutputBufferFlush: * @out: a buffered output * * flushes the output I/O channel * * Returns the number of byte written or -1 in case of error. */ int xmlOutputBufferFlush(xmlOutputBufferPtr out) { int nbchars = 0, ret = 0; if ((out == NULL) || (out->error)) return(-1); /* * first handle encoding stuff. */ if ((out->conv != NULL) && (out->encoder != NULL)) { /* * convert as much as possible to the parser reading buffer. */ nbchars = xmlCharEncOutFunc(out->encoder, out->conv, out->buffer); if (nbchars < 0) { xmlIOErr(XML_IO_ENCODER, NULL); out->error = XML_IO_ENCODER; return(-1); } } /* * second flush the stuff to the I/O channel */ if ((out->conv != NULL) && (out->encoder != NULL) && (out->writecallback != NULL)) { ret = out->writecallback(out->context, (const char *)out->conv->content, out->conv->use); if (ret >= 0) xmlBufferShrink(out->conv, ret); } else if (out->writecallback != NULL) { ret = out->writecallback(out->context, (const char *)out->buffer->content, out->buffer->use); if (ret >= 0) xmlBufferShrink(out->buffer, ret); } if (ret < 0) { xmlIOErr(XML_IO_FLUSH, NULL); out->error = XML_IO_FLUSH; return(ret); } out->written += ret; #ifdef DEBUG_INPUT xmlGenericError(xmlGenericErrorContext, "I/O: flushed %d chars\n", ret); #endif return(ret); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlParserGetDirectory: * @filename: the path to a file * * lookup the directory for that file * * Returns a new allocated string containing the directory, or NULL. */ char * xmlParserGetDirectory(const char *filename) { char *ret = NULL; char dir[1024]; char *cur; char sep = '/'; #ifdef _WIN32_WCE /* easy way by now ... wince does not have dirs! */ return NULL; #endif if (xmlInputCallbackInitialized == 0) xmlRegisterDefaultInputCallbacks(); if (filename == NULL) return(NULL); #if defined(WIN32) && !defined(__CYGWIN__) sep = '\\'; #endif strncpy(dir, filename, 1023); dir[1023] = 0; cur = &dir[strlen(dir)]; while (cur > dir) { if (*cur == sep) break; cur --; } if (*cur == sep) { if (cur == dir) dir[1] = 0; else *cur = 0; ret = xmlMemStrdup(dir); } else { if (getcwd(dir, 1024) != NULL) { dir[1023] = 0; ret = xmlMemStrdup(dir); } } return(ret); } /**************************************************************** * * * External entities loading * * * ****************************************************************/ /** * xmlCheckHTTPInput: * @ctxt: an XML parser context * @ret: an XML parser input * * Check an input in case it was created from an HTTP stream, in that * case it will handle encoding and update of the base URL in case of * redirection. It also checks for HTTP errors in which case the input * is cleanly freed up and an appropriate error is raised in context * * Returns the input or NULL in case of HTTP error. */ xmlParserInputPtr xmlCheckHTTPInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr ret) { #ifdef LIBXML_HTTP_ENABLED if ((ret != NULL) && (ret->buf != NULL) && (ret->buf->readcallback == xmlIOHTTPRead) && (ret->buf->context != NULL)) { const char *encoding; const char *redir; const char *mime; int code; code = xmlNanoHTTPReturnCode(ret->buf->context); if (code >= 400) { /* fatal error */ if (ret->filename != NULL) __xmlLoaderErr(ctxt, "failed to load HTTP resource \"%s\"\n", (const char *) ret->filename); else __xmlLoaderErr(ctxt, "failed to load HTTP resource\n", NULL); xmlFreeInputStream(ret); ret = NULL; } else { mime = xmlNanoHTTPMimeType(ret->buf->context); if ((xmlStrstr(BAD_CAST mime, BAD_CAST "/xml")) || (xmlStrstr(BAD_CAST mime, BAD_CAST "+xml"))) { encoding = xmlNanoHTTPEncoding(ret->buf->context); if (encoding != NULL) { xmlCharEncodingHandlerPtr handler; handler = xmlFindCharEncodingHandler(encoding); if (handler != NULL) { xmlSwitchInputEncoding(ctxt, ret, handler); } else { __xmlErrEncoding(ctxt, XML_ERR_UNKNOWN_ENCODING, "Unknown encoding %s", BAD_CAST encoding, NULL); } if (ret->encoding == NULL) ret->encoding = xmlStrdup(BAD_CAST encoding); } #if 0 } else if (xmlStrstr(BAD_CAST mime, BAD_CAST "html")) { #endif } redir = xmlNanoHTTPRedir(ret->buf->context); if (redir != NULL) { if (ret->filename != NULL) xmlFree((xmlChar *) ret->filename); if (ret->directory != NULL) { xmlFree((xmlChar *) ret->directory); ret->directory = NULL; } ret->filename = (char *) xmlStrdup((const xmlChar *) redir); } } } #else (void)ctxt; #endif return(ret); } static int xmlNoNetExists(const char *URL) { const char *path; if (URL == NULL) return(0); if (!xmlStrncasecmp(BAD_CAST URL, BAD_CAST "file://localhost/", 17)) #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &URL[17]; #else path = &URL[16]; #endif else if (!xmlStrncasecmp(BAD_CAST URL, BAD_CAST "file:///", 8)) { #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__) path = &URL[8]; #else path = &URL[7]; #endif } else path = URL; return xmlCheckFilename(path); } #ifdef LIBXML_CATALOG_ENABLED /** * xmlResolveResourceFromCatalog: * @URL: the URL for the entity to load * @ID: the System ID for the entity to load * @ctxt: the context in which the entity is called or NULL * * Resolves the URL and ID against the appropriate catalog. * This function is used by xmlDefaultExternalEntityLoader and * xmlNoNetExternalEntityLoader. * * Returns a new allocated URL, or NULL. */ xmlChar * xmlResolveResourceFromCatalog(const char *URL, const char *ID, xmlParserCtxtPtr ctxt) { xmlChar *resource = NULL; xmlCatalogAllow pref; /* * If the resource doesn't exists as a file, * try to load it from the resource pointed in the catalogs */ pref = xmlCatalogGetDefaults(); if ((pref != XML_CATA_ALLOW_NONE) && (!xmlNoNetExists(URL))) { /* * Do a local lookup */ if ((ctxt != NULL) && (ctxt->catalogs != NULL) && ((pref == XML_CATA_ALLOW_ALL) || (pref == XML_CATA_ALLOW_DOCUMENT))) { resource = xmlCatalogLocalResolve(ctxt->catalogs, (const xmlChar *)ID, (const xmlChar *)URL); } /* * Try a global lookup */ if ((resource == NULL) && ((pref == XML_CATA_ALLOW_ALL) || (pref == XML_CATA_ALLOW_GLOBAL))) { resource = xmlCatalogResolve((const xmlChar *)ID, (const xmlChar *)URL); } if ((resource == NULL) && (URL != NULL)) resource = xmlStrdup((const xmlChar *) URL); /* * TODO: do an URI lookup on the reference */ if ((resource != NULL) && (!xmlNoNetExists((const char *)resource))) { xmlChar *tmp = NULL; if ((ctxt != NULL) && (ctxt->catalogs != NULL) && ((pref == XML_CATA_ALLOW_ALL) || (pref == XML_CATA_ALLOW_DOCUMENT))) { tmp = xmlCatalogLocalResolveURI(ctxt->catalogs, resource); } if ((tmp == NULL) && ((pref == XML_CATA_ALLOW_ALL) || (pref == XML_CATA_ALLOW_GLOBAL))) { tmp = xmlCatalogResolveURI(resource); } if (tmp != NULL) { xmlFree(resource); resource = tmp; } } } return resource; } #endif /** * xmlDefaultExternalEntityLoader: * @URL: the URL for the entity to load * @ID: the System ID for the entity to load * @ctxt: the context in which the entity is called or NULL * * By default we don't load external entitites, yet. * * Returns a new allocated xmlParserInputPtr, or NULL. */ static xmlParserInputPtr xmlDefaultExternalEntityLoader(const char *URL, const char *ID, xmlParserCtxtPtr ctxt) { xmlParserInputPtr ret = NULL; xmlChar *resource = NULL; #ifdef DEBUG_EXTERNAL_ENTITIES xmlGenericError(xmlGenericErrorContext, "xmlDefaultExternalEntityLoader(%s, xxx)\n", URL); #endif if ((ctxt != NULL) && (ctxt->options & XML_PARSE_NONET)) { int options = ctxt->options; ctxt->options -= XML_PARSE_NONET; ret = xmlNoNetExternalEntityLoader(URL, ID, ctxt); ctxt->options = options; return(ret); } #ifdef LIBXML_CATALOG_ENABLED resource = xmlResolveResourceFromCatalog(URL, ID, ctxt); #endif if (resource == NULL) resource = (xmlChar *) URL; if (resource == NULL) { if (ID == NULL) ID = "NULL"; __xmlLoaderErr(ctxt, "failed to load external entity \"%s\"\n", ID); return (NULL); } ret = xmlNewInputFromFile(ctxt, (const char *) resource); if ((resource != NULL) && (resource != (xmlChar *) URL)) xmlFree(resource); return (ret); } static xmlExternalEntityLoader xmlCurrentExternalEntityLoader = xmlDefaultExternalEntityLoader; /** * xmlSetExternalEntityLoader: * @f: the new entity resolver function * * Changes the defaultexternal entity resolver function for the application */ void xmlSetExternalEntityLoader(xmlExternalEntityLoader f) { xmlCurrentExternalEntityLoader = f; } /** * xmlGetExternalEntityLoader: * * Get the default external entity resolver function for the application * * Returns the xmlExternalEntityLoader function pointer */ xmlExternalEntityLoader xmlGetExternalEntityLoader(void) { return(xmlCurrentExternalEntityLoader); } /** * xmlLoadExternalEntity: * @URL: the URL for the entity to load * @ID: the Public ID for the entity to load * @ctxt: the context in which the entity is called or NULL * * Load an external entity, note that the use of this function for * unparsed entities may generate problems * * Returns the xmlParserInputPtr or NULL */ xmlParserInputPtr xmlLoadExternalEntity(const char *URL, const char *ID, xmlParserCtxtPtr ctxt) { if ((URL != NULL) && (xmlNoNetExists(URL) == 0)) { char *canonicFilename; xmlParserInputPtr ret; canonicFilename = (char *) xmlCanonicPath((const xmlChar *) URL); if (canonicFilename == NULL) { xmlIOErrMemory("building canonical path\n"); return(NULL); } ret = xmlCurrentExternalEntityLoader(canonicFilename, ID, ctxt); xmlFree(canonicFilename); return(ret); } return(xmlCurrentExternalEntityLoader(URL, ID, ctxt)); } /************************************************************************ * * * Disabling Network access * * * ************************************************************************/ /** * xmlNoNetExternalEntityLoader: * @URL: the URL for the entity to load * @ID: the System ID for the entity to load * @ctxt: the context in which the entity is called or NULL * * A specific entity loader disabling network accesses, though still * allowing local catalog accesses for resolution. * * Returns a new allocated xmlParserInputPtr, or NULL. */ xmlParserInputPtr xmlNoNetExternalEntityLoader(const char *URL, const char *ID, xmlParserCtxtPtr ctxt) { xmlParserInputPtr input = NULL; xmlChar *resource = NULL; #ifdef LIBXML_CATALOG_ENABLED resource = xmlResolveResourceFromCatalog(URL, ID, ctxt); #endif if (resource == NULL) resource = (xmlChar *) URL; if (resource != NULL) { if ((!xmlStrncasecmp(BAD_CAST resource, BAD_CAST "ftp://", 6)) || (!xmlStrncasecmp(BAD_CAST resource, BAD_CAST "http://", 7))) { xmlIOErr(XML_IO_NETWORK_ATTEMPT, (const char *) resource); if (resource != (xmlChar *) URL) xmlFree(resource); return(NULL); } } input = xmlDefaultExternalEntityLoader((const char *) resource, ID, ctxt); if (resource != (xmlChar *) URL) xmlFree(resource); return(input); } #define bottom_xmlIO #include "elfgcchack.h" xdmf-2.1.dfsg.1/Utilities/vtklibxml2/.NoDartCoverage0000644000175000017500000000004711606020250023433 0ustar amckinstryamckinstry# do not do coverage in this directory xdmf-2.1.dfsg.1/Utilities/vtklibxml2/triostr.c0000644000175000017500000012642511606020250022452 0ustar amckinstryamckinstry/************************************************************************* * * $Id: triostr.c,v 1.2 2007-04-24 17:23:33 king Exp $ * * Copyright (C) 2001 Bjorn Reese and Daniel Stenberg. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER. * ************************************************************************/ /************************************************************************* * Include files */ #include #include #include #include #include #include "triodef.h" #include "triostr.h" /************************************************************************* * Definitions */ #if !defined(TRIO_STRING_PUBLIC) # define TRIO_STRING_PUBLIC TRIO_PUBLIC #endif #if !defined(TRIO_STRING_PRIVATE) # define TRIO_STRING_PRIVATE TRIO_PRIVATE #endif #if !defined(NULL) # define NULL 0 #endif #if !defined(NIL) # define NIL ((char)0) #endif #if !defined(FALSE) # define FALSE (1 == 0) # define TRUE (! FALSE) #endif #if !defined(BOOLEAN_T) # define BOOLEAN_T int #endif #if defined(TRIO_COMPILER_SUPPORTS_C99) # define USE_STRTOD # define USE_STRTOF #elif defined(TRIO_COMPILER_MSVC) # define USE_STRTOD #endif #if defined(TRIO_PLATFORM_UNIX) # define USE_STRCASECMP # define USE_STRNCASECMP # if defined(TRIO_PLATFORM_SUNOS) # define USE_SYS_ERRLIST # else # define USE_STRERROR # endif # if defined(TRIO_PLATFORM_QNX) # define strcasecmp(x,y) stricmp(x,y) # define strncasecmp(x,y,n) strnicmp(x,y,n) # endif #elif defined(TRIO_PLATFORM_WIN32) # define USE_STRCASECMP # define strcasecmp(x,y) strcmpi(x,y) #endif #if !(defined(TRIO_PLATFORM_SUNOS)) # define USE_TOLOWER # define USE_TOUPPER #endif /************************************************************************* * Structures */ struct _trio_string_t { char *content; size_t length; size_t allocated; }; /************************************************************************* * Constants */ #if !defined(TRIO_MINIMAL) static TRIO_CONST char rcsid[] = "@(#)$Id: triostr.c,v 1.2 2007-04-24 17:23:33 king Exp $"; #endif /************************************************************************* * Static String Functions */ #if defined(TRIO_DOCUMENTATION) # include "doc/doc_static.h" #endif /** @addtogroup StaticStrings @{ */ /** Create new string. @param size Size of new string. @return Pointer to string, or NULL if allocation failed. */ TRIO_STRING_PUBLIC char * trio_create TRIO_ARGS1((size), size_t size) { return (char *)TRIO_MALLOC(size); } /** Destroy string. @param string String to be freed. */ TRIO_STRING_PUBLIC void trio_destroy TRIO_ARGS1((string), char *string) { if (string) { TRIO_FREE(string); } } /** Count the number of characters in a string. @param string String to measure. @return Number of characters in @string. */ TRIO_STRING_PUBLIC size_t trio_length TRIO_ARGS1((string), TRIO_CONST char *string) { return strlen(string); } #if !defined(TRIO_MINIMAL) /** Append @p source at the end of @p target. @param target Target string. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chunk with sufficient room to contain the @p target string and @p source string. @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ TRIO_STRING_PUBLIC int trio_append TRIO_ARGS2((target, source), char *target, TRIO_CONST char *source) { assert(target); assert(source); return (strcat(target, source) != NULL); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Append at most @p max characters from @p source to @p target. @param target Target string. @param max Maximum number of characters to append. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chuck with sufficient room to contain the @p target string and the @p source string (at most @p max characters). @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ TRIO_STRING_PUBLIC int trio_append_max TRIO_ARGS3((target, max, source), char *target, size_t max, TRIO_CONST char *source) { size_t length; assert(target); assert(source); length = trio_length(target); if (max > length) { strncat(target, source, max - length - 1); } return TRUE; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Determine if a string contains a substring. @param string String to be searched. @param substring String to be found. @return Boolean value indicating success or failure. */ TRIO_STRING_PUBLIC int trio_contains TRIO_ARGS2((string, substring), TRIO_CONST char *string, TRIO_CONST char *substring) { assert(string); assert(substring); return (0 != strstr(string, substring)); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Copy @p source to @p target. @param target Target string. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chunk with sufficient room to contain the @p source string. @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ TRIO_STRING_PUBLIC int trio_copy TRIO_ARGS2((target, source), char *target, TRIO_CONST char *source) { assert(target); assert(source); (void)strcpy(target, source); return TRUE; } #endif /* !defined(TRIO_MINIMAL) */ /** Copy at most @p max characters from @p source to @p target. @param target Target string. @param max Maximum number of characters to append. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chunk with sufficient room to contain the @p source string (at most @p max characters). @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ TRIO_STRING_PUBLIC int trio_copy_max TRIO_ARGS3((target, max, source), char *target, size_t max, TRIO_CONST char *source) { assert(target); assert(source); assert(max > 0); /* Includes != 0 */ (void)strncpy(target, source, max - 1); target[max - 1] = (char)0; return TRUE; } /* * TrioDuplicateMax */ TRIO_STRING_PRIVATE char * TrioDuplicateMax TRIO_ARGS2((source, size), TRIO_CONST char *source, size_t size) { char *target; assert(source); /* Make room for string plus a terminating zero */ size++; target = trio_create(size); if (target) { trio_copy_max(target, size, source); } return target; } /** Duplicate @p source. @param source Source string. @return A copy of the @p source string. @post @p target will be zero terminated. */ TRIO_STRING_PUBLIC char * trio_duplicate TRIO_ARGS1((source), TRIO_CONST char *source) { return TrioDuplicateMax(source, trio_length(source)); } #if !defined(TRIO_MINIMAL) /** Duplicate at most @p max characters of @p source. @param source Source string. @param max Maximum number of characters to duplicate. @return A copy of the @p source string. @post @p target will be zero terminated. */ TRIO_STRING_PUBLIC char * trio_duplicate_max TRIO_ARGS2((source, max), TRIO_CONST char *source, size_t max) { size_t length; assert(source); assert(max > 0); length = trio_length(source); if (length > max) { length = max; } return TrioDuplicateMax(source, length); } #endif /* !defined(TRIO_MINIMAL) */ /** Compare if two strings are equal. @param first First string. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-insensitive comparison. */ TRIO_STRING_PUBLIC int trio_equal TRIO_ARGS2((first, second), TRIO_CONST char *first, TRIO_CONST char *second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { #if defined(USE_STRCASECMP) return (0 == strcasecmp(first, second)); #else while ((*first != NIL) && (*second != NIL)) { if (trio_to_upper(*first) != trio_to_upper(*second)) { break; } first++; second++; } return ((*first == NIL) && (*second == NIL)); #endif } return FALSE; } /** Compare if two strings are equal. @param first First string. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-sensitive comparison. */ TRIO_STRING_PUBLIC int trio_equal_case TRIO_ARGS2((first, second), TRIO_CONST char *first, TRIO_CONST char *second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { return (0 == strcmp(first, second)); } return FALSE; } #if !defined(TRIO_MINIMAL) /** Compare if two strings up until the first @p max characters are equal. @param first First string. @param max Maximum number of characters to compare. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-sensitive comparison. */ TRIO_STRING_PUBLIC int trio_equal_case_max TRIO_ARGS3((first, max, second), TRIO_CONST char *first, size_t max, TRIO_CONST char *second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { return (0 == strncmp(first, second, max)); } return FALSE; } #endif /* !defined(TRIO_MINIMAL) */ /** Compare if two strings are equal. @param first First string. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Collating characters are considered equal. */ TRIO_STRING_PUBLIC int trio_equal_locale TRIO_ARGS2((first, second), TRIO_CONST char *first, TRIO_CONST char *second) { assert(first); assert(second); #if defined(LC_COLLATE) return (strcoll(first, second) == 0); #else return trio_equal(first, second); #endif } /** Compare if two strings up until the first @p max characters are equal. @param first First string. @param max Maximum number of characters to compare. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-insensitive comparison. */ TRIO_STRING_PUBLIC int trio_equal_max TRIO_ARGS3((first, max, second), TRIO_CONST char *first, size_t max, TRIO_CONST char *second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { #if defined(USE_STRNCASECMP) return (0 == strncasecmp(first, second, max)); #else /* Not adequately tested yet */ size_t cnt = 0; while ((*first != NIL) && (*second != NIL) && (cnt <= max)) { if (trio_to_upper(*first) != trio_to_upper(*second)) { break; } first++; second++; cnt++; } return ((cnt == max) || ((*first == NIL) && (*second == NIL))); #endif } return FALSE; } /** Provide a textual description of an error code (errno). @param error_number Error number. @return Textual description of @p error_number. */ TRIO_STRING_PUBLIC TRIO_CONST char * trio_error TRIO_ARGS1((error_number), int error_number) { #if defined(USE_STRERROR) return strerror(error_number); #elif defined(USE_SYS_ERRLIST) extern char *sys_errlist[]; extern int sys_nerr; return ((error_number < 0) || (error_number >= sys_nerr)) ? "unknown" : sys_errlist[error_number]; #else return "unknown"; #endif } #if !defined(TRIO_MINIMAL) /** Format the date/time according to @p format. @param target Target string. @param max Maximum number of characters to format. @param format Formatting string. @param datetime Date/time structure. @return Number of formatted characters. The formatting string accepts the same specifiers as the standard C function strftime. */ TRIO_STRING_PUBLIC size_t trio_format_date_max TRIO_ARGS4((target, max, format, datetime), char *target, size_t max, TRIO_CONST char *format, TRIO_CONST struct tm *datetime) { assert(target); assert(format); assert(datetime); assert(max > 0); return strftime(target, max, format, datetime); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Calculate a hash value for a string. @param string String to be calculated on. @param type Hash function. @return Calculated hash value. @p type can be one of the following @li @c TRIO_HASH_PLAIN Plain hash function. */ TRIO_STRING_PUBLIC unsigned long trio_hash TRIO_ARGS2((string, type), TRIO_CONST char *string, int type) { unsigned long value = 0L; char ch; assert(string); switch (type) { case TRIO_HASH_PLAIN: while ( (ch = *string++) != NIL ) { value *= 31; value += (unsigned long)ch; } break; default: assert(FALSE); break; } return value; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Find first occurrence of a character in a string. @param string String to be searched. @param character Character to be found. @param A pointer to the found character, or NULL if character was not found. */ TRIO_STRING_PUBLIC char * trio_index TRIO_ARGS2((string, character), TRIO_CONST char *string, int character) { assert(string); return strchr(string, character); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Find last occurrence of a character in a string. @param string String to be searched. @param character Character to be found. @param A pointer to the found character, or NULL if character was not found. */ TRIO_STRING_PUBLIC char * trio_index_last TRIO_ARGS2((string, character), TRIO_CONST char *string, int character) { assert(string); return strchr(string, character); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Convert the alphabetic letters in the string to lower-case. @param target String to be converted. @return Number of processed characters (converted or not). */ TRIO_STRING_PUBLIC int trio_lower TRIO_ARGS1((target), char *target) { assert(target); return trio_span_function(target, target, trio_to_lower); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Compare two strings using wildcards. @param string String to be searched. @param pattern Pattern, including wildcards, to search for. @return Boolean value indicating success or failure. Case-insensitive comparison. The following wildcards can be used @li @c * Match any number of characters. @li @c ? Match a single character. */ TRIO_STRING_PUBLIC int trio_match TRIO_ARGS2((string, pattern), TRIO_CONST char *string, TRIO_CONST char *pattern) { assert(string); assert(pattern); for (; ('*' != *pattern); ++pattern, ++string) { if (NIL == *string) { return (NIL == *pattern); } if ((trio_to_upper((int)*string) != trio_to_upper((int)*pattern)) && ('?' != *pattern)) { return FALSE; } } /* two-line patch to prevent *too* much recursiveness: */ while ('*' == pattern[1]) pattern++; do { if ( trio_match(string, &pattern[1]) ) { return TRUE; } } while (*string++); return FALSE; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Compare two strings using wildcards. @param string String to be searched. @param pattern Pattern, including wildcards, to search for. @return Boolean value indicating success or failure. Case-sensitive comparison. The following wildcards can be used @li @c * Match any number of characters. @li @c ? Match a single character. */ TRIO_STRING_PUBLIC int trio_match_case TRIO_ARGS2((string, pattern), TRIO_CONST char *string, TRIO_CONST char *pattern) { assert(string); assert(pattern); for (; ('*' != *pattern); ++pattern, ++string) { if (NIL == *string) { return (NIL == *pattern); } if ((*string != *pattern) && ('?' != *pattern)) { return FALSE; } } /* two-line patch to prevent *too* much recursiveness: */ while ('*' == pattern[1]) pattern++; do { if ( trio_match_case(string, &pattern[1]) ) { return TRUE; } } while (*string++); return FALSE; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Execute a function on each character in string. @param target Target string. @param source Source string. @param Function Function to be executed. @return Number of processed characters. */ TRIO_STRING_PUBLIC size_t trio_span_function TRIO_ARGS3((target, source, Function), char *target, TRIO_CONST char *source, int (*Function) TRIO_PROTO((int))) { size_t count = 0; assert(target); assert(source); assert(Function); while (*source != NIL) { *target++ = Function(*source++); count++; } return count; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Search for a substring in a string. @param string String to be searched. @param substring String to be found. @return Pointer to first occurrence of @p substring in @p string, or NULL if no match was found. */ TRIO_STRING_PUBLIC char * trio_substring TRIO_ARGS2((string, substring), TRIO_CONST char *string, TRIO_CONST char *substring) { assert(string); assert(substring); return strstr(string, substring); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Search for a substring in the first @p max characters of a string. @param string String to be searched. @param max Maximum characters to be searched. @param substring String to be found. @return Pointer to first occurrence of @p substring in @p string, or NULL if no match was found. */ TRIO_STRING_PUBLIC char * trio_substring_max TRIO_ARGS3((string, max, substring), TRIO_CONST char *string, size_t max, TRIO_CONST char *substring) { size_t count; size_t size; char *result = NULL; assert(string); assert(substring); size = trio_length(substring); if (size <= max) { for (count = 0; count <= max - size; count++) { if (trio_equal_max(substring, size, &string[count])) { result = (char *)&string[count]; break; } } } return result; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Tokenize string. @param string String to be tokenized. @param tokens String containing list of delimiting characters. @return Start of new token. @warning @p string will be destroyed. */ TRIO_STRING_PUBLIC char * trio_tokenize TRIO_ARGS2((string, delimiters), char *string, TRIO_CONST char *delimiters) { assert(delimiters); return strtok(string, delimiters); } #endif /* !defined(TRIO_MINIMAL) */ /** Convert string to floating-point number. @param source String to be converted. @param endp Pointer to end of the converted string. @return A floating-point number. The following Extended Backus-Naur form is used @verbatim double ::= [ ] ( | | ) [ [ ] ] number ::= 1*( ) digit ::= ( '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ) exponential ::= ( 'e' | 'E' ) sign ::= ( '-' | '+' ) decimal_point ::= '.' @endverbatim */ /* FIXME: Add EBNF for hex-floats */ TRIO_STRING_PUBLIC trio_long_double_t trio_to_long_double TRIO_ARGS2((source, endp), TRIO_CONST char *source, char **endp) { #if defined(USE_STRTOLD) return strtold(source, endp); #else int isNegative = FALSE; int isExponentNegative = FALSE; trio_long_double_t integer = 0.0; trio_long_double_t fraction = 0.0; unsigned long exponent = 0; trio_long_double_t base; trio_long_double_t fracdiv = 1.0; trio_long_double_t value = 0.0; /* First try hex-floats */ if ((source[0] == '0') && ((source[1] == 'x') || (source[1] == 'X'))) { base = 16.0; source += 2; while (isxdigit((int)*source)) { integer *= base; integer += (isdigit((int)*source) ? (*source - '0') : 10 + (trio_to_upper((int)*source) - 'A')); source++; } if (*source == '.') { source++; while (isxdigit((int)*source)) { fracdiv /= base; fraction += fracdiv * (isdigit((int)*source) ? (*source - '0') : 10 + (trio_to_upper((int)*source) - 'A')); source++; } if ((*source == 'p') || (*source == 'P')) { source++; if ((*source == '+') || (*source == '-')) { isExponentNegative = (*source == '-'); source++; } while (isdigit((int)*source)) { exponent *= 10; exponent += (*source - '0'); source++; } } } /* For later use with exponent */ base = 2.0; } else /* Then try normal decimal floats */ { base = 10.0; isNegative = (*source == '-'); /* Skip sign */ if ((*source == '+') || (*source == '-')) source++; /* Integer part */ while (isdigit((int)*source)) { integer *= base; integer += (*source - '0'); source++; } if (*source == '.') { source++; /* skip decimal point */ while (isdigit((int)*source)) { fracdiv /= base; fraction += (*source - '0') * fracdiv; source++; } } if ((*source == 'e') || (*source == 'E') #if TRIO_MICROSOFT || (*source == 'd') || (*source == 'D') #endif ) { source++; /* Skip exponential indicator */ isExponentNegative = (*source == '-'); if ((*source == '+') || (*source == '-')) source++; while (isdigit((int)*source)) { exponent *= (int)base; exponent += (*source - '0'); source++; } } } value = integer + fraction; if (exponent != 0) { if (isExponentNegative) value /= pow(base, (double)exponent); else value *= pow(base, (double)exponent); } if (isNegative) value = -value; if (endp) *endp = (char *)source; return value; #endif } /** Convert string to floating-point number. @param source String to be converted. @param endp Pointer to end of the converted string. @return A floating-point number. See @ref trio_to_long_double. */ TRIO_STRING_PUBLIC double trio_to_double TRIO_ARGS2((source, endp), TRIO_CONST char *source, char **endp) { #if defined(USE_STRTOD) return strtod(source, endp); #else return (double)trio_to_long_double(source, endp); #endif } #if !defined(TRIO_MINIMAL) /** Convert string to floating-point number. @param source String to be converted. @param endp Pointer to end of the converted string. @return A floating-point number. See @ref trio_to_long_double. */ TRIO_STRING_PUBLIC float trio_to_float TRIO_ARGS2((source, endp), TRIO_CONST char *source, char **endp) { #if defined(USE_STRTOF) return strtof(source, endp); #else return (float)trio_to_long_double(source, endp); #endif } #endif /* !defined(TRIO_MINIMAL) */ /** Convert string to signed integer. @param string String to be converted. @param endp Pointer to end of converted string. @param base Radix number of number. */ TRIO_STRING_PUBLIC long trio_to_long TRIO_ARGS3((string, endp, base), TRIO_CONST char *string, char **endp, int base) { assert(string); assert((base >= 2) && (base <= 36)); return strtol(string, endp, base); } #if !defined(TRIO_MINIMAL) /** Convert one alphabetic letter to lower-case. @param source The letter to be converted. @return The converted letter. */ TRIO_STRING_PUBLIC int trio_to_lower TRIO_ARGS1((source), int source) { #if defined(USE_TOLOWER) return tolower(source); #else /* Does not handle locales or non-contiguous alphabetic characters */ return ((source >= (int)'A') && (source <= (int)'Z')) ? source - 'A' + 'a' : source; #endif } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Convert string to unsigned integer. @param string String to be converted. @param endp Pointer to end of converted string. @param base Radix number of number. */ TRIO_STRING_PUBLIC unsigned long trio_to_unsigned_long TRIO_ARGS3((string, endp, base), TRIO_CONST char *string, char **endp, int base) { assert(string); assert((base >= 2) && (base <= 36)); return strtoul(string, endp, base); } #endif /* !defined(TRIO_MINIMAL) */ /** Convert one alphabetic letter to upper-case. @param source The letter to be converted. @return The converted letter. */ TRIO_STRING_PUBLIC int trio_to_upper TRIO_ARGS1((source), int source) { #if defined(USE_TOUPPER) return toupper(source); #else /* Does not handle locales or non-contiguous alphabetic characters */ return ((source >= (int)'a') && (source <= (int)'z')) ? source - 'a' + 'A' : source; #endif } #if !defined(TRIO_MINIMAL) /** Convert the alphabetic letters in the string to upper-case. @param target The string to be converted. @return The number of processed characters (converted or not). */ TRIO_STRING_PUBLIC int trio_upper TRIO_ARGS1((target), char *target) { assert(target); return trio_span_function(target, target, trio_to_upper); } #endif /* !defined(TRIO_MINIMAL) */ /** @} End of StaticStrings */ /************************************************************************* * Dynamic String Functions */ #if defined(TRIO_DOCUMENTATION) # include "doc/doc_dynamic.h" #endif /** @addtogroup DynamicStrings @{ */ /* * TrioStringAlloc */ TRIO_STRING_PRIVATE trio_string_t * TrioStringAlloc(TRIO_NOARGS) { trio_string_t *self; self = (trio_string_t *)TRIO_MALLOC(sizeof(trio_string_t)); if (self) { self->content = NULL; self->length = 0; self->allocated = 0; } return self; } /* * TrioStringGrow * * The size of the string will be increased by 'delta' characters. If * 'delta' is zero, the size will be doubled. */ TRIO_STRING_PRIVATE BOOLEAN_T TrioStringGrow TRIO_ARGS2((self, delta), trio_string_t *self, size_t delta) { BOOLEAN_T status = FALSE; char *new_content; size_t new_size; new_size = (delta == 0) ? ( (self->allocated == 0) ? 1 : self->allocated * 2 ) : self->allocated + delta; new_content = (char *)TRIO_REALLOC(self->content, new_size); if (new_content) { self->content = new_content; self->allocated = new_size; status = TRUE; } return status; } #if !defined(TRIO_MINIMAL) /* * TrioStringGrowTo * * The size of the string will be increased to 'length' plus one characters. * If 'length' is less than the original size, the original size will be * used (that is, the size of the string is never decreased). */ TRIO_STRING_PRIVATE BOOLEAN_T TrioStringGrowTo TRIO_ARGS2((self, length), trio_string_t *self, size_t length) { length++; /* Room for terminating zero */ return (self->allocated < length) ? TrioStringGrow(self, length - self->allocated) : TRUE; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /** Create a new dynamic string. @param initial_size Initial size of the buffer. @return Newly allocated dynamic string, or NULL if memory allocation failed. */ TRIO_STRING_PUBLIC trio_string_t * trio_string_create TRIO_ARGS1((initial_size), int initial_size) { trio_string_t *self; self = TrioStringAlloc(); if (self) { if (TrioStringGrow(self, (size_t)((initial_size > 0) ? initial_size : 1))) { self->content[0] = (char)0; self->allocated = initial_size; } else { trio_string_destroy(self); self = NULL; } } return self; } #endif /* !defined(TRIO_MINIMAL) */ /** Deallocate the dynamic string and its contents. @param self Dynamic string */ TRIO_STRING_PUBLIC void trio_string_destroy TRIO_ARGS1((self), trio_string_t *self) { assert(self); if (self) { trio_destroy(self->content); TRIO_FREE(self); } } #if !defined(TRIO_MINIMAL) /** Get a pointer to the content. @param self Dynamic string. @param offset Offset into content. @return Pointer to the content. @p Offset can be zero, positive, or negative. If @p offset is zero, then the start of the content will be returned. If @p offset is positive, then a pointer to @p offset number of characters from the beginning of the content is returned. If @p offset is negative, then a pointer to @p offset number of characters from the ending of the string, starting at the terminating zero, is returned. */ TRIO_STRING_PUBLIC char * trio_string_get TRIO_ARGS2((self, offset), trio_string_t *self, int offset) { char *result = NULL; assert(self); if (self->content != NULL) { if (self->length == 0) { (void)trio_string_length(self); } if (offset >= 0) { if (offset > (int)self->length) { offset = self->length; } } else { offset += self->length + 1; if (offset < 0) { offset = 0; } } result = &(self->content[offset]); } return result; } #endif /* !defined(TRIO_MINIMAL) */ /** Extract the content. @param self Dynamic String @return Content of dynamic string. The content is removed from the dynamic string. This enables destruction of the dynamic string without deallocation of the content. */ TRIO_STRING_PUBLIC char * trio_string_extract TRIO_ARGS1((self), trio_string_t *self) { char *result; assert(self); result = self->content; /* FIXME: Allocate new empty buffer? */ self->content = NULL; self->length = self->allocated = 0; return result; } #if !defined(TRIO_MINIMAL) /** Set the content of the dynamic string. @param self Dynamic String @param buffer The new content. Sets the content of the dynamic string to a copy @p buffer. An existing content will be deallocated first, if necessary. @remark This function will make a copy of @p buffer. You are responsible for deallocating @p buffer yourself. */ TRIO_STRING_PUBLIC void trio_xstring_set TRIO_ARGS2((self, buffer), trio_string_t *self, char *buffer) { assert(self); trio_destroy(self->content); self->content = trio_duplicate(buffer); } #endif /* !defined(TRIO_MINIMAL) */ /* * trio_string_size */ TRIO_STRING_PUBLIC int trio_string_size TRIO_ARGS1((self), trio_string_t *self) { assert(self); return self->allocated; } /* * trio_string_terminate */ TRIO_STRING_PUBLIC void trio_string_terminate TRIO_ARGS1((self), trio_string_t *self) { trio_xstring_append_char(self, 0); } #if !defined(TRIO_MINIMAL) /** Append the second string to the first. @param self Dynamic string to be modified. @param other Dynamic string to copy from. @return Boolean value indicating success or failure. */ TRIO_STRING_PUBLIC int trio_string_append TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { size_t length; assert(self); assert(other); length = self->length + other->length; if (!TrioStringGrowTo(self, length)) goto error; trio_copy(&self->content[self->length], other->content); self->length = length; return TRUE; error: return FALSE; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_append */ TRIO_STRING_PUBLIC int trio_xstring_append TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { size_t length; assert(self); assert(other); length = self->length + trio_length(other); if (!TrioStringGrowTo(self, length)) goto error; trio_copy(&self->content[self->length], other); self->length = length; return TRUE; error: return FALSE; } #endif /* !defined(TRIO_MINIMAL) */ /* * trio_xstring_append_char */ TRIO_STRING_PUBLIC int trio_xstring_append_char TRIO_ARGS2((self, character), trio_string_t *self, char character) { assert(self); if ((int)self->length >= trio_string_size(self)) { if (!TrioStringGrow(self, 0)) goto error; } self->content[self->length] = character; self->length++; return TRUE; error: return FALSE; } #if !defined(TRIO_MINIMAL) /** Search for the first occurrence of second parameter in the first. @param self Dynamic string to be modified. @param other Dynamic string to copy from. @return Boolean value indicating success or failure. */ TRIO_STRING_PUBLIC int trio_string_contains TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { assert(self); assert(other); return trio_contains(self->content, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_contains */ TRIO_STRING_PUBLIC int trio_xstring_contains TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { assert(self); assert(other); return trio_contains(self->content, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_copy */ TRIO_STRING_PUBLIC int trio_string_copy TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { assert(self); assert(other); self->length = 0; return trio_string_append(self, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_copy */ TRIO_STRING_PUBLIC int trio_xstring_copy TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { assert(self); assert(other); self->length = 0; return trio_xstring_append(self, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_duplicate */ TRIO_STRING_PUBLIC trio_string_t * trio_string_duplicate TRIO_ARGS1((other), trio_string_t *other) { trio_string_t *self; assert(other); self = TrioStringAlloc(); if (self) { self->content = TrioDuplicateMax(other->content, other->length); if (self->content) { self->length = other->length; self->allocated = self->length + 1; } else { self->length = self->allocated = 0; } } return self; } #endif /* !defined(TRIO_MINIMAL) */ /* * trio_xstring_duplicate */ TRIO_STRING_PUBLIC trio_string_t * trio_xstring_duplicate TRIO_ARGS1((other), TRIO_CONST char *other) { trio_string_t *self; assert(other); self = TrioStringAlloc(); if (self) { self->content = TrioDuplicateMax(other, trio_length(other)); if (self->content) { self->length = trio_length(self->content); self->allocated = self->length + 1; } else { self->length = self->allocated = 0; } } return self; } #if !defined(TRIO_MINIMAL) /* * trio_string_equal */ TRIO_STRING_PUBLIC int trio_string_equal TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { assert(self); assert(other); return trio_equal(self->content, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_equal */ TRIO_STRING_PUBLIC int trio_xstring_equal TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { assert(self); assert(other); return trio_equal(self->content, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_equal_max */ TRIO_STRING_PUBLIC int trio_string_equal_max TRIO_ARGS3((self, max, other), trio_string_t *self, size_t max, trio_string_t *other) { assert(self); assert(other); return trio_equal_max(self->content, max, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_equal_max */ TRIO_STRING_PUBLIC int trio_xstring_equal_max TRIO_ARGS3((self, max, other), trio_string_t *self, size_t max, TRIO_CONST char *other) { assert(self); assert(other); return trio_equal_max(self->content, max, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_equal_case */ TRIO_STRING_PUBLIC int trio_string_equal_case TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { assert(self); assert(other); return trio_equal_case(self->content, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_equal_case */ TRIO_STRING_PUBLIC int trio_xstring_equal_case TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { assert(self); assert(other); return trio_equal_case(self->content, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_equal_case_max */ TRIO_STRING_PUBLIC int trio_string_equal_case_max TRIO_ARGS3((self, max, other), trio_string_t *self, size_t max, trio_string_t *other) { assert(self); assert(other); return trio_equal_case_max(self->content, max, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_equal_case_max */ TRIO_STRING_PUBLIC int trio_xstring_equal_case_max TRIO_ARGS3((self, max, other), trio_string_t *self, size_t max, TRIO_CONST char *other) { assert(self); assert(other); return trio_equal_case_max(self->content, max, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_format_data_max */ TRIO_STRING_PUBLIC size_t trio_string_format_date_max TRIO_ARGS4((self, max, format, datetime), trio_string_t *self, size_t max, TRIO_CONST char *format, TRIO_CONST struct tm *datetime) { assert(self); return trio_format_date_max(self->content, max, format, datetime); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_index */ TRIO_STRING_PUBLIC char * trio_string_index TRIO_ARGS2((self, character), trio_string_t *self, int character) { assert(self); return trio_index(self->content, character); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_index_last */ TRIO_STRING_PUBLIC char * trio_string_index_last TRIO_ARGS2((self, character), trio_string_t *self, int character) { assert(self); return trio_index_last(self->content, character); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_length */ TRIO_STRING_PUBLIC int trio_string_length TRIO_ARGS1((self), trio_string_t *self) { assert(self); if (self->length == 0) { self->length = trio_length(self->content); } return self->length; } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_lower */ TRIO_STRING_PUBLIC int trio_string_lower TRIO_ARGS1((self), trio_string_t *self) { assert(self); return trio_lower(self->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_match */ TRIO_STRING_PUBLIC int trio_string_match TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { assert(self); assert(other); return trio_match(self->content, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_match */ TRIO_STRING_PUBLIC int trio_xstring_match TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { assert(self); assert(other); return trio_match(self->content, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_match_case */ TRIO_STRING_PUBLIC int trio_string_match_case TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { assert(self); assert(other); return trio_match_case(self->content, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_match_case */ TRIO_STRING_PUBLIC int trio_xstring_match_case TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { assert(self); assert(other); return trio_match_case(self->content, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_substring */ TRIO_STRING_PUBLIC char * trio_string_substring TRIO_ARGS2((self, other), trio_string_t *self, trio_string_t *other) { assert(self); assert(other); return trio_substring(self->content, other->content); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_xstring_substring */ TRIO_STRING_PUBLIC char * trio_xstring_substring TRIO_ARGS2((self, other), trio_string_t *self, TRIO_CONST char *other) { assert(self); assert(other); return trio_substring(self->content, other); } #endif /* !defined(TRIO_MINIMAL) */ #if !defined(TRIO_MINIMAL) /* * trio_string_upper */ TRIO_STRING_PUBLIC int trio_string_upper TRIO_ARGS1((self), trio_string_t *self) { assert(self); return trio_upper(self->content); } #endif /* !defined(TRIO_MINIMAL) */ /** @} End of DynamicStrings */ xdmf-2.1.dfsg.1/Utilities/vtklibxml2/globals.c0000644000175000017500000007776111606020250022377 0ustar amckinstryamckinstry/* * globals.c: definition and handling of the set of global variables * of the library * * The bottom of this file is automatically generated by build_glob.py * based on the description file global.data * * See Copyright for the status of this software. * * Gary Pennington * daniel@veillard.com */ #define IN_LIBXML #include "libxml.h" #ifdef HAVE_STDLIB_H #include #endif #include #include #include #include /* #define DEBUG_GLOBALS */ /* * Helpful Macro */ #ifdef LIBXML_THREAD_ENABLED #define IS_MAIN_THREAD (xmlIsMainThread()) #else #define IS_MAIN_THREAD 1 #endif /* * Mutex to protect "ForNewThreads" variables */ static xmlMutexPtr xmlThrDefMutex = NULL; /** * xmlInitGlobals: * * Additional initialisation for multi-threading */ void xmlInitGlobals(void) { xmlThrDefMutex = xmlNewMutex(); } /** * xmlCleanupGlobals: * * Additional cleanup for multi-threading */ void xmlCleanupGlobals(void) { if (xmlThrDefMutex != NULL) { xmlFreeMutex(xmlThrDefMutex); xmlThrDefMutex = NULL; } } /************************************************************************ * * * All the user accessible global variables of the library * * * ************************************************************************/ /* * Memory allocation routines */ #undef xmlFree #undef xmlMalloc #undef xmlMallocAtomic #undef xmlMemStrdup #undef xmlRealloc #if defined(DEBUG_MEMORY_LOCATION) || defined(DEBUG_MEMORY) xmlFreeFunc vtk_libxml2_xmlFree = (xmlFreeFunc) xmlMemFree; xmlMallocFunc vtk_libxml2_xmlMalloc = (xmlMallocFunc) xmlMemMalloc; xmlMallocFunc vtk_libxml2_xmlMallocAtomic = (xmlMallocFunc) xmlMemMalloc; xmlReallocFunc vtk_libxml2_xmlRealloc = (xmlReallocFunc) xmlMemRealloc; xmlStrdupFunc vtk_libxml2_xmlMemStrdup = (xmlStrdupFunc) xmlMemoryStrdup; #else /** * xmlFree: * @mem: an already allocated block of memory * * The variable holding the libxml free() implementation */ xmlFreeFunc vtk_libxml2_xmlFree = (xmlFreeFunc) free; /** * xmlMalloc: * @size: the size requested in bytes * * The variable holding the libxml malloc() implementation * * Returns a pointer to the newly allocated block or NULL in case of error */ xmlMallocFunc vtk_libxml2_xmlMalloc = (xmlMallocFunc) malloc; /** * xmlMallocAtomic: * @size: the size requested in bytes * * The variable holding the libxml malloc() implementation for atomic * data (i.e. blocks not containings pointers), useful when using a * garbage collecting allocator. * * Returns a pointer to the newly allocated block or NULL in case of error */ xmlMallocFunc vtk_libxml2_xmlMallocAtomic = (xmlMallocFunc) malloc; /** * xmlRealloc: * @mem: an already allocated block of memory * @size: the new size requested in bytes * * The variable holding the libxml realloc() implementation * * Returns a pointer to the newly reallocated block or NULL in case of error */ xmlReallocFunc vtk_libxml2_xmlRealloc = (xmlReallocFunc) realloc; /** * xmlMemStrdup: * @str: a zero terminated string * * The variable holding the libxml strdup() implementation * * Returns the copy of the string or NULL in case of error */ xmlStrdupFunc vtk_libxml2_xmlMemStrdup = (xmlStrdupFunc) xmlStrdup; #endif /* DEBUG_MEMORY_LOCATION || DEBUG_MEMORY */ #include #include #include #undef docbDefaultSAXHandler #undef htmlDefaultSAXHandler #undef oldXMLWDcompatibility #undef xmlBufferAllocScheme #undef xmlDefaultBufferSize #undef xmlDefaultSAXHandler #undef xmlDefaultSAXLocator #undef xmlDoValidityCheckingDefaultValue #undef xmlGenericError #undef xmlStructuredError #undef xmlGenericErrorContext #undef xmlGetWarningsDefaultValue #undef xmlIndentTreeOutput #undef xmlTreeIndentString #undef xmlKeepBlanksDefaultValue #undef xmlLineNumbersDefaultValue #undef xmlLoadExtDtdDefaultValue #undef xmlParserDebugEntities #undef xmlParserVersion #undef xmlPedanticParserDefaultValue #undef xmlSaveNoEmptyTags #undef xmlSubstituteEntitiesDefaultValue #undef xmlRegisterNodeDefaultValue #undef xmlDeregisterNodeDefaultValue #undef xmlLastError #undef xmlParserInputBufferCreateFilenameValue #undef xmlOutputBufferCreateFilenameValue /** * xmlParserVersion: * * Constant string describing the internal version of the library */ const char *vtk_libxml2_xmlParserVersion = LIBXML_VERSION_STRING LIBXML_VERSION_EXTRA; /** * xmlBufferAllocScheme: * * Global setting, default allocation policy for buffers, default is * XML_BUFFER_ALLOC_EXACT */ xmlBufferAllocationScheme vtk_libxml2_xmlBufferAllocScheme = XML_BUFFER_ALLOC_EXACT; static xmlBufferAllocationScheme xmlBufferAllocSchemeThrDef = XML_BUFFER_ALLOC_EXACT; /** * xmlDefaultBufferSize: * * Global setting, default buffer size. Default value is BASE_BUFFER_SIZE */ int vtk_libxml2_xmlDefaultBufferSize = BASE_BUFFER_SIZE; static int xmlDefaultBufferSizeThrDef = BASE_BUFFER_SIZE; /* * Parser defaults */ /** * oldXMLWDcompatibility: * * Global setting, DEPRECATED. */ int vtk_libxml2_oldXMLWDcompatibility = 0; /* DEPRECATED */ /** * xmlParserDebugEntities: * * Global setting, asking the parser to print out debugging informations. * while handling entities. * Disabled by default */ int vtk_libxml2_xmlParserDebugEntities = 0; static int xmlParserDebugEntitiesThrDef = 0; /** * xmlDoValidityCheckingDefaultValue: * * Global setting, indicate that the parser should work in validating mode. * Disabled by default. */ int vtk_libxml2_xmlDoValidityCheckingDefaultValue = 0; static int xmlDoValidityCheckingDefaultValueThrDef = 0; /** * xmlGetWarningsDefaultValue: * * Global setting, indicate that the parser should provide warnings. * Activated by default. */ int vtk_libxml2_xmlGetWarningsDefaultValue = 1; static int xmlGetWarningsDefaultValueThrDef = 1; /** * xmlLoadExtDtdDefaultValue: * * Global setting, indicate that the parser should load DTD while not * validating. * Disabled by default. */ int vtk_libxml2_xmlLoadExtDtdDefaultValue = 0; static int xmlLoadExtDtdDefaultValueThrDef = 0; /** * xmlPedanticParserDefaultValue: * * Global setting, indicate that the parser be pedantic * Disabled by default. */ int vtk_libxml2_xmlPedanticParserDefaultValue = 0; static int xmlPedanticParserDefaultValueThrDef = 0; /** * xmlLineNumbersDefaultValue: * * Global setting, indicate that the parser should store the line number * in the content field of elements in the DOM tree. * Disabled by default since this may not be safe for old classes of * applicaton. */ int vtk_libxml2_xmlLineNumbersDefaultValue = 0; static int xmlLineNumbersDefaultValueThrDef = 0; /** * xmlKeepBlanksDefaultValue: * * Global setting, indicate that the parser should keep all blanks * nodes found in the content * Activated by default, this is actually needed to have the parser * conformant to the XML Recommendation, however the option is kept * for some applications since this was libxml1 default behaviour. */ int vtk_libxml2_xmlKeepBlanksDefaultValue = 1; static int xmlKeepBlanksDefaultValueThrDef = 1; /** * xmlSubstituteEntitiesDefaultValue: * * Global setting, indicate that the parser should not generate entity * references but replace them with the actual content of the entity * Disabled by default, this should be activated when using XPath since * the XPath data model requires entities replacement and the XPath * engine does not handle entities references transparently. */ int vtk_libxml2_xmlSubstituteEntitiesDefaultValue = 0; static int xmlSubstituteEntitiesDefaultValueThrDef = 0; xmlRegisterNodeFunc vtk_libxml2_xmlRegisterNodeDefaultValue = NULL; static xmlRegisterNodeFunc xmlRegisterNodeDefaultValueThrDef = NULL; xmlDeregisterNodeFunc vtk_libxml2_xmlDeregisterNodeDefaultValue = NULL; static xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValueThrDef = NULL; xmlParserInputBufferCreateFilenameFunc vtk_libxml2_xmlParserInputBufferCreateFilenameValue = NULL; static xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValueThrDef = NULL; xmlOutputBufferCreateFilenameFunc vtk_libxml2_xmlOutputBufferCreateFilenameValue = NULL; static xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValueThrDef = NULL; /* * Error handling */ /* xmlGenericErrorFunc xmlGenericError = xmlGenericErrorDefaultFunc; */ /* Must initialize xmlGenericError in xmlInitParser */ void XMLCDECL xmlGenericErrorDefaultFunc (void *ctx ATTRIBUTE_UNUSED, const char *msg, ...); /** * xmlGenericError: * * Global setting: function used for generic error callbacks */ xmlGenericErrorFunc vtk_libxml2_xmlGenericError = xmlGenericErrorDefaultFunc; static xmlGenericErrorFunc xmlGenericErrorThrDef = xmlGenericErrorDefaultFunc; /** * xmlStructuredError: * * Global setting: function used for structured error callbacks */ xmlStructuredErrorFunc vtk_libxml2_xmlStructuredError = NULL; static xmlStructuredErrorFunc xmlStructuredErrorThrDef = NULL; /** * xmlGenericErrorContext: * * Global setting passed to generic error callbacks */ void *vtk_libxml2_xmlGenericErrorContext = NULL; static void *xmlGenericErrorContextThrDef = NULL; xmlError vtk_libxml2_xmlLastError = {0}; /* Init avoids common block on Mac */ /* * output defaults */ /** * xmlIndentTreeOutput: * * Global setting, asking the serializer to indent the output tree by default * Enabled by default */ int vtk_libxml2_xmlIndentTreeOutput = 1; static int xmlIndentTreeOutputThrDef = 1; /** * xmlTreeIndentString: * * The string used to do one-level indent. By default is equal to " " (two spaces) */ const char *vtk_libxml2_xmlTreeIndentString = " "; static const char *xmlTreeIndentStringThrDef = " "; /** * xmlSaveNoEmptyTags: * * Global setting, asking the serializer to not output empty tags * as but . those two forms are undistinguishable * once parsed. * Disabled by default */ int vtk_libxml2_xmlSaveNoEmptyTags = 0; static int xmlSaveNoEmptyTagsThrDef = 0; #ifdef LIBXML_SAX1_ENABLED /** * xmlDefaultSAXHandler: * * Default SAX version1 handler for XML, builds the DOM tree */ xmlSAXHandlerV1 vtk_libxml2_xmlDefaultSAXHandler = { xmlSAX2InternalSubset, xmlSAX2IsStandalone, xmlSAX2HasInternalSubset, xmlSAX2HasExternalSubset, xmlSAX2ResolveEntity, xmlSAX2GetEntity, xmlSAX2EntityDecl, xmlSAX2NotationDecl, xmlSAX2AttributeDecl, xmlSAX2ElementDecl, xmlSAX2UnparsedEntityDecl, xmlSAX2SetDocumentLocator, xmlSAX2StartDocument, xmlSAX2EndDocument, xmlSAX2StartElement, xmlSAX2EndElement, xmlSAX2Reference, xmlSAX2Characters, xmlSAX2Characters, xmlSAX2ProcessingInstruction, xmlSAX2Comment, xmlParserWarning, xmlParserError, xmlParserError, xmlSAX2GetParameterEntity, xmlSAX2CDataBlock, xmlSAX2ExternalSubset, 0, }; #endif /* LIBXML_SAX1_ENABLED */ /** * xmlDefaultSAXLocator: * * The default SAX Locator * { getPublicId, getSystemId, getLineNumber, getColumnNumber} */ xmlSAXLocator vtk_libxml2_xmlDefaultSAXLocator = { xmlSAX2GetPublicId, xmlSAX2GetSystemId, xmlSAX2GetLineNumber, xmlSAX2GetColumnNumber }; #ifdef LIBXML_HTML_ENABLED /** * htmlDefaultSAXHandler: * * Default old SAX v1 handler for HTML, builds the DOM tree */ xmlSAXHandlerV1 vtk_libxml2_htmlDefaultSAXHandler = { xmlSAX2InternalSubset, NULL, NULL, NULL, NULL, xmlSAX2GetEntity, NULL, NULL, NULL, NULL, NULL, xmlSAX2SetDocumentLocator, xmlSAX2StartDocument, xmlSAX2EndDocument, xmlSAX2StartElement, xmlSAX2EndElement, NULL, xmlSAX2Characters, xmlSAX2IgnorableWhitespace, xmlSAX2ProcessingInstruction, xmlSAX2Comment, xmlParserWarning, xmlParserError, xmlParserError, xmlSAX2GetParameterEntity, xmlSAX2CDataBlock, NULL, 0, }; #endif /* LIBXML_HTML_ENABLED */ #ifdef LIBXML_DOCB_ENABLED /** * docbDefaultSAXHandler: * * Default old SAX v1 handler for SGML DocBook, builds the DOM tree */ xmlSAXHandlerV1 vtk_libxml2_docbDefaultSAXHandler = { xmlSAX2InternalSubset, xmlSAX2IsStandalone, xmlSAX2HasInternalSubset, xmlSAX2HasExternalSubset, xmlSAX2ResolveEntity, xmlSAX2GetEntity, xmlSAX2EntityDecl, NULL, NULL, NULL, NULL, xmlSAX2SetDocumentLocator, xmlSAX2StartDocument, xmlSAX2EndDocument, xmlSAX2StartElement, xmlSAX2EndElement, xmlSAX2Reference, xmlSAX2Characters, xmlSAX2IgnorableWhitespace, NULL, xmlSAX2Comment, xmlParserWarning, xmlParserError, xmlParserError, xmlSAX2GetParameterEntity, NULL, NULL, 0, }; #endif /* LIBXML_DOCB_ENABLED */ /** * xmlInitializeGlobalState: * @gs: a pointer to a newly allocated global state * * xmlInitializeGlobalState() initialize a global state with all the * default values of the library. */ void xmlInitializeGlobalState(xmlGlobalStatePtr gs) { #ifdef DEBUG_GLOBALS fprintf(stderr, "Initializing globals at %lu for thread %d\n", (unsigned long) gs, xmlGetThreadId()); #endif /* * Perform initialization as required by libxml */ if (xmlThrDefMutex == NULL) xmlInitGlobals(); xmlMutexLock(xmlThrDefMutex); #if defined(LIBXML_DOCB_ENABLED) && defined(LIBXML_LEGACY_ENABLED) && defined(LIBXML_SAX1_ENABLED) initdocbDefaultSAXHandler(&gs->docbDefaultSAXHandler); #endif #if defined(LIBXML_HTML_ENABLED) && defined(LIBXML_LEGACY_ENABLED) inithtmlDefaultSAXHandler(&gs->htmlDefaultSAXHandler); #endif gs->oldXMLWDcompatibility = 0; gs->xmlBufferAllocScheme = xmlBufferAllocSchemeThrDef; gs->xmlDefaultBufferSize = xmlDefaultBufferSizeThrDef; #if defined(LIBXML_SAX1_ENABLED) && defined(LIBXML_LEGACY_ENABLED) initxmlDefaultSAXHandler(&gs->xmlDefaultSAXHandler, 1); #endif /* LIBXML_SAX1_ENABLED */ gs->xmlDefaultSAXLocator.getPublicId = xmlSAX2GetPublicId; gs->xmlDefaultSAXLocator.getSystemId = xmlSAX2GetSystemId; gs->xmlDefaultSAXLocator.getLineNumber = xmlSAX2GetLineNumber; gs->xmlDefaultSAXLocator.getColumnNumber = xmlSAX2GetColumnNumber; gs->xmlDoValidityCheckingDefaultValue = xmlDoValidityCheckingDefaultValueThrDef; #if defined(DEBUG_MEMORY_LOCATION) | defined(DEBUG_MEMORY) gs->xmlFree = (xmlFreeFunc) vtk_libxml2_xmlMemFree; gs->xmlMalloc = (xmlMallocFunc) vtk_libxml2_xmlMemMalloc; gs->xmlMallocAtomic = (xmlMallocFunc) vtk_libxml2_xmlMemMalloc; gs->xmlRealloc = (xmlReallocFunc) vtk_libxml2_xmlMemRealloc; gs->xmlMemStrdup = (xmlStrdupFunc) vtk_libxml2_xmlMemoryStrdup; #else gs->xmlFree = (xmlFreeFunc) free; gs->xmlMalloc = (xmlMallocFunc) malloc; gs->xmlMallocAtomic = (xmlMallocFunc) malloc; gs->xmlRealloc = (xmlReallocFunc) realloc; gs->xmlMemStrdup = (xmlStrdupFunc) xmlStrdup; #endif gs->xmlGetWarningsDefaultValue = xmlGetWarningsDefaultValueThrDef; gs->xmlIndentTreeOutput = xmlIndentTreeOutputThrDef; gs->xmlTreeIndentString = xmlTreeIndentStringThrDef; gs->xmlKeepBlanksDefaultValue = xmlKeepBlanksDefaultValueThrDef; gs->xmlLineNumbersDefaultValue = xmlLineNumbersDefaultValueThrDef; gs->xmlLoadExtDtdDefaultValue = xmlLoadExtDtdDefaultValueThrDef; gs->xmlParserDebugEntities = xmlParserDebugEntitiesThrDef; gs->xmlParserVersion = LIBXML_VERSION_STRING; gs->xmlPedanticParserDefaultValue = xmlPedanticParserDefaultValueThrDef; gs->xmlSaveNoEmptyTags = xmlSaveNoEmptyTagsThrDef; gs->xmlSubstituteEntitiesDefaultValue = xmlSubstituteEntitiesDefaultValueThrDef; gs->xmlGenericError = xmlGenericErrorThrDef; gs->xmlStructuredError = xmlStructuredErrorThrDef; gs->xmlGenericErrorContext = xmlGenericErrorContextThrDef; gs->xmlRegisterNodeDefaultValue = xmlRegisterNodeDefaultValueThrDef; gs->xmlDeregisterNodeDefaultValue = xmlDeregisterNodeDefaultValueThrDef; gs->xmlParserInputBufferCreateFilenameValue = xmlParserInputBufferCreateFilenameValueThrDef; gs->xmlOutputBufferCreateFilenameValue = xmlOutputBufferCreateFilenameValueThrDef; memset(&gs->xmlLastError, 0, sizeof(xmlError)); xmlMutexUnlock(xmlThrDefMutex); } #define docbDefaultSAXHandler vtk_libxml2_docbDefaultSAXHandler #define htmlDefaultSAXHandler vtk_libxml2_htmlDefaultSAXHandler #define xmlLastError vtk_libxml2_xmlLastError #define oldXMLWDcompatibility vtk_libxml2_oldXMLWDcompatibility #define xmlBufferAllocScheme vtk_libxml2_xmlBufferAllocScheme #define xmlDefaultBufferSize vtk_libxml2_xmlDefaultBufferSize #define xmlDefaultSAXHandler vtk_libxml2_xmlDefaultSAXHandler #define xmlDefaultSAXLocator vtk_libxml2_xmlDefaultSAXLocator #define xmlDoValidityCheckingDefaultValue vtk_libxml2_xmlDoValidityCheckingDefaultValue #define xmlGenericError vtk_libxml2_xmlGenericError #define xmlStructuredError vtk_libxml2_xmlStructuredError #define xmlGenericErrorContext vtk_libxml2_xmlGenericErrorContext #define xmlGetWarningsDefaultValue vtk_libxml2_xmlGetWarningsDefaultValue #define xmlIndentTreeOutput vtk_libxml2_xmlIndentTreeOutput #define xmlTreeIndentString vtk_libxml2_xmlTreeIndentString #define xmlKeepBlanksDefaultValue vtk_libxml2_xmlKeepBlanksDefaultValue #define xmlLineNumbersDefaultValue vtk_libxml2_xmlLineNumbersDefaultValue #define xmlLoadExtDtdDefaultValue vtk_libxml2_xmlLoadExtDtdDefaultValue #define xmlParserDebugEntities vtk_libxml2_xmlParserDebugEntities #define xmlParserVersion vtk_libxml2_xmlParserVersion #define xmlPedanticParserDefaultValue vtk_libxml2_xmlPedanticParserDefaultValue #define xmlSaveNoEmptyTags vtk_libxml2_xmlSaveNoEmptyTags #define xmlSubstituteEntitiesDefaultValue vtk_libxml2_xmlSubstituteEntitiesDefaultValue #define xmlRegisterNodeDefaultValue vtk_libxml2_xmlRegisterNodeDefaultValue #define xmlDeregisterNodeDefaultValue vtk_libxml2_xmlDeregisterNodeDefaultValue #define xmlParserInputBufferCreateFilenameValue vtk_libxml2_xmlParserInputBufferCreateFilenameValue #define xmlOutputBufferCreateFilenameValue vtk_libxml2_xmlOutputBufferCreateFilenameValue #define xmlMalloc vtk_libxml2_xmlMalloc #define xmlMallocAtomic vtk_libxml2_xmlMallocAtomic #define xmlRealloc vtk_libxml2_xmlRealloc #define xmlFree vtk_libxml2_xmlFree #define xmlMemStrdup vtk_libxml2_xmlMemStrdup /** * DOC_DISABLE : we ignore missing doc for the xmlThrDef functions, * those are really internal work */ void xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler) { xmlMutexLock(xmlThrDefMutex); xmlGenericErrorContextThrDef = ctx; if (handler != NULL) xmlGenericErrorThrDef = handler; else xmlGenericErrorThrDef = xmlGenericErrorDefaultFunc; xmlMutexUnlock(xmlThrDefMutex); } void xmlThrDefSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler) { xmlMutexLock(xmlThrDefMutex); xmlGenericErrorContextThrDef = ctx; xmlStructuredErrorThrDef = handler; xmlMutexUnlock(xmlThrDefMutex); } /** * xmlRegisterNodeDefault: * @func: function pointer to the new RegisterNodeFunc * * Registers a callback for node creation * * Returns the old value of the registration function */ xmlRegisterNodeFunc xmlRegisterNodeDefault(xmlRegisterNodeFunc func) { xmlRegisterNodeFunc old = xmlRegisterNodeDefaultValue; __xmlRegisterCallbacks = 1; xmlRegisterNodeDefaultValue = func; return(old); } xmlRegisterNodeFunc xmlThrDefRegisterNodeDefault(xmlRegisterNodeFunc func) { xmlRegisterNodeFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlRegisterNodeDefaultValueThrDef; __xmlRegisterCallbacks = 1; xmlRegisterNodeDefaultValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } /** * xmlDeregisterNodeDefault: * @func: function pointer to the new DeregisterNodeFunc * * Registers a callback for node destruction * * Returns the previous value of the deregistration function */ xmlDeregisterNodeFunc xmlDeregisterNodeDefault(xmlDeregisterNodeFunc func) { xmlDeregisterNodeFunc old = xmlDeregisterNodeDefaultValue; __xmlRegisterCallbacks = 1; xmlDeregisterNodeDefaultValue = func; return(old); } xmlDeregisterNodeFunc xmlThrDefDeregisterNodeDefault(xmlDeregisterNodeFunc func) { xmlDeregisterNodeFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlDeregisterNodeDefaultValueThrDef; __xmlRegisterCallbacks = 1; xmlDeregisterNodeDefaultValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } xmlParserInputBufferCreateFilenameFunc xmlThrDefParserInputBufferCreateFilenameDefault(xmlParserInputBufferCreateFilenameFunc func) { xmlParserInputBufferCreateFilenameFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlParserInputBufferCreateFilenameValueThrDef; if (old == NULL) { old = __xmlParserInputBufferCreateFilename; } xmlParserInputBufferCreateFilenameValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } xmlOutputBufferCreateFilenameFunc xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func) { xmlOutputBufferCreateFilenameFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlOutputBufferCreateFilenameValueThrDef; #ifdef LIBXML_OUTPUT_ENABLED if (old == NULL) { old = __xmlOutputBufferCreateFilename; } #endif xmlOutputBufferCreateFilenameValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } #ifdef LIBXML_DOCB_ENABLED #undef docbDefaultSAXHandler xmlSAXHandlerV1 * __docbDefaultSAXHandler(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_docbDefaultSAXHandler); else return (&xmlGetGlobalState()->docbDefaultSAXHandler); } #endif #ifdef LIBXML_HTML_ENABLED #undef htmlDefaultSAXHandler xmlSAXHandlerV1 * __htmlDefaultSAXHandler(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_htmlDefaultSAXHandler); else return (&xmlGetGlobalState()->htmlDefaultSAXHandler); } #endif #undef xmlLastError xmlError * __xmlLastError(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlLastError); else return (&xmlGetGlobalState()->xmlLastError); } /* * The following memory routines were apparently lost at some point, * and were re-inserted at this point on June 10, 2004. Hope it's * the right place for them :-) */ #if defined(LIBXML_THREAD_ALLOC_ENABLED) && defined(LIBXML_THREAD_ENABLED) #undef xmlMalloc xmlMallocFunc * __xmlMalloc(void){ if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlMalloc); else return (&xmlGetGlobalState()->xmlMalloc); } #undef xmlMallocAtomic xmlMallocFunc * __xmlMallocAtomic(void){ if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlMallocAtomic); else return (&xmlGetGlobalState()->xmlMallocAtomic); } #undef xmlRealloc xmlReallocFunc * __xmlRealloc(void){ if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlRealloc); else return (&xmlGetGlobalState()->xmlRealloc); } #undef xmlFree xmlFreeFunc * __xmlFree(void){ if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlFree); else return (&xmlGetGlobalState()->xmlFree); } xmlStrdupFunc * __xmlMemStrdup(void){ if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlMemStrdup); else return (&xmlGetGlobalState()->xmlMemStrdup); } #endif /* * Everything starting from the line below is * Automatically generated by build_glob.py. * Do not modify the previous line. */ #undef oldXMLWDcompatibility int * __oldXMLWDcompatibility(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_oldXMLWDcompatibility); else return (&xmlGetGlobalState()->oldXMLWDcompatibility); } #undef xmlBufferAllocScheme xmlBufferAllocationScheme * __xmlBufferAllocScheme(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlBufferAllocScheme); else return (&xmlGetGlobalState()->xmlBufferAllocScheme); } xmlBufferAllocationScheme xmlThrDefBufferAllocScheme(xmlBufferAllocationScheme v) { xmlBufferAllocationScheme ret; xmlMutexLock(xmlThrDefMutex); ret = xmlBufferAllocSchemeThrDef; xmlBufferAllocSchemeThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlDefaultBufferSize int * __xmlDefaultBufferSize(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlDefaultBufferSize); else return (&xmlGetGlobalState()->xmlDefaultBufferSize); } int xmlThrDefDefaultBufferSize(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlDefaultBufferSizeThrDef; xmlDefaultBufferSizeThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #ifdef LIBXML_SAX1_ENABLED #undef xmlDefaultSAXHandler xmlSAXHandlerV1 * __xmlDefaultSAXHandler(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlDefaultSAXHandler); else return (&xmlGetGlobalState()->xmlDefaultSAXHandler); } #endif /* LIBXML_SAX1_ENABLED */ #undef xmlDefaultSAXLocator xmlSAXLocator * __xmlDefaultSAXLocator(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlDefaultSAXLocator); else return (&xmlGetGlobalState()->xmlDefaultSAXLocator); } #undef xmlDoValidityCheckingDefaultValue int * __xmlDoValidityCheckingDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlDoValidityCheckingDefaultValue); else return (&xmlGetGlobalState()->xmlDoValidityCheckingDefaultValue); } int xmlThrDefDoValidityCheckingDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlDoValidityCheckingDefaultValueThrDef; xmlDoValidityCheckingDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlGenericError xmlGenericErrorFunc * __xmlGenericError(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlGenericError); else return (&xmlGetGlobalState()->xmlGenericError); } #undef xmlStructuredError xmlStructuredErrorFunc * __xmlStructuredError(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlStructuredError); else return (&xmlGetGlobalState()->xmlStructuredError); } #undef xmlGenericErrorContext void * * __xmlGenericErrorContext(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlGenericErrorContext); else return (&xmlGetGlobalState()->xmlGenericErrorContext); } #undef xmlGetWarningsDefaultValue int * __xmlGetWarningsDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlGetWarningsDefaultValue); else return (&xmlGetGlobalState()->xmlGetWarningsDefaultValue); } int xmlThrDefGetWarningsDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlGetWarningsDefaultValueThrDef; xmlGetWarningsDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlIndentTreeOutput int * __xmlIndentTreeOutput(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlIndentTreeOutput); else return (&xmlGetGlobalState()->xmlIndentTreeOutput); } int xmlThrDefIndentTreeOutput(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlIndentTreeOutputThrDef; xmlIndentTreeOutputThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlTreeIndentString const char * * __xmlTreeIndentString(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlTreeIndentString); else return (&xmlGetGlobalState()->xmlTreeIndentString); } const char * xmlThrDefTreeIndentString(const char * v) { const char * ret; xmlMutexLock(xmlThrDefMutex); ret = xmlTreeIndentStringThrDef; xmlTreeIndentStringThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlKeepBlanksDefaultValue int * __xmlKeepBlanksDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlKeepBlanksDefaultValue); else return (&xmlGetGlobalState()->xmlKeepBlanksDefaultValue); } int xmlThrDefKeepBlanksDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlKeepBlanksDefaultValueThrDef; xmlKeepBlanksDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlLineNumbersDefaultValue int * __xmlLineNumbersDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlLineNumbersDefaultValue); else return (&xmlGetGlobalState()->xmlLineNumbersDefaultValue); } int xmlThrDefLineNumbersDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlLineNumbersDefaultValueThrDef; xmlLineNumbersDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlLoadExtDtdDefaultValue int * __xmlLoadExtDtdDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlLoadExtDtdDefaultValue); else return (&xmlGetGlobalState()->xmlLoadExtDtdDefaultValue); } int xmlThrDefLoadExtDtdDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlLoadExtDtdDefaultValueThrDef; xmlLoadExtDtdDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlParserDebugEntities int * __xmlParserDebugEntities(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlParserDebugEntities); else return (&xmlGetGlobalState()->xmlParserDebugEntities); } int xmlThrDefParserDebugEntities(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlParserDebugEntitiesThrDef; xmlParserDebugEntitiesThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlParserVersion const char * * __xmlParserVersion(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlParserVersion); else return (&xmlGetGlobalState()->xmlParserVersion); } #undef xmlPedanticParserDefaultValue int * __xmlPedanticParserDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlPedanticParserDefaultValue); else return (&xmlGetGlobalState()->xmlPedanticParserDefaultValue); } int xmlThrDefPedanticParserDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlPedanticParserDefaultValueThrDef; xmlPedanticParserDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlSaveNoEmptyTags int * __xmlSaveNoEmptyTags(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlSaveNoEmptyTags); else return (&xmlGetGlobalState()->xmlSaveNoEmptyTags); } int xmlThrDefSaveNoEmptyTags(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlSaveNoEmptyTagsThrDef; xmlSaveNoEmptyTagsThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlSubstituteEntitiesDefaultValue int * __xmlSubstituteEntitiesDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlSubstituteEntitiesDefaultValue); else return (&xmlGetGlobalState()->xmlSubstituteEntitiesDefaultValue); } int xmlThrDefSubstituteEntitiesDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlSubstituteEntitiesDefaultValueThrDef; xmlSubstituteEntitiesDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlRegisterNodeDefaultValue xmlRegisterNodeFunc * __xmlRegisterNodeDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlRegisterNodeDefaultValue); else return (&xmlGetGlobalState()->xmlRegisterNodeDefaultValue); } #undef xmlDeregisterNodeDefaultValue xmlDeregisterNodeFunc * __xmlDeregisterNodeDefaultValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlDeregisterNodeDefaultValue); else return (&xmlGetGlobalState()->xmlDeregisterNodeDefaultValue); } #undef xmlParserInputBufferCreateFilenameValue xmlParserInputBufferCreateFilenameFunc * __xmlParserInputBufferCreateFilenameValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlParserInputBufferCreateFilenameValue); else return (&xmlGetGlobalState()->xmlParserInputBufferCreateFilenameValue); } #undef xmlOutputBufferCreateFilenameValue xmlOutputBufferCreateFilenameFunc * __xmlOutputBufferCreateFilenameValue(void) { if (IS_MAIN_THREAD) return (&vtk_libxml2_xmlOutputBufferCreateFilenameValue); else return (&xmlGetGlobalState()->xmlOutputBufferCreateFilenameValue); } #define bottom_globals #include "elfgcchack.h" xdmf-2.1.dfsg.1/Utilities/vtklibxml2/nanohttp.c0000644000175000017500000014042011606020250022566 0ustar amckinstryamckinstry/* * nanohttp.c: minimalist HTTP GET implementation to fetch external subsets. * focuses on size, streamability, reentrancy and portability * * This is clearly not a general purpose HTTP implementation * If you look for one, check: * http://www.w3.org/Library/ * * See Copyright for the status of this software. * * daniel@veillard.com */ #define NEED_SOCKETS #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_HTTP_ENABLED #include #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_SOCKET_H #include #endif #ifdef HAVE_NETINET_IN_H #include #endif #ifdef HAVE_ARPA_INET_H #include #endif #ifdef HAVE_NETDB_H #include #endif #ifdef HAVE_RESOLV_H #ifdef HAVE_ARPA_NAMESER_H #include #endif #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_ERRNO_H #include #endif #ifdef HAVE_SYS_TIME_H #include #endif #ifdef HAVE_SYS_SELECT_H #include #endif #ifdef HAVE_STRINGS_H #include #endif #ifdef SUPPORT_IP6 #include #endif #include "vtk_libxml2_zlib.h" #ifdef VMS #include #define XML_SOCKLEN_T unsigned int #define SOCKET int #endif #ifdef __MINGW32__ #define _WINSOCKAPI_ #include #include #undef XML_SOCKLEN_T #define XML_SOCKLEN_T unsigned int #endif #include #include #include #include /* for xmlStr(n)casecmp() */ #include #include #include /** * A couple portability macros */ #ifndef _WINSOCKAPI_ #ifndef __BEOS__ #define closesocket(s) close(s) #endif #define SOCKET int #endif #ifdef __BEOS__ #ifndef PF_INET #define PF_INET AF_INET #endif #endif #ifndef XML_SOCKLEN_T #define XML_SOCKLEN_T unsigned int #endif #ifndef SOCKET #define SOCKET int #endif #ifdef STANDALONE #define DEBUG_HTTP #define xmlStrncasecmp(a, b, n) strncasecmp((char *)a, (char *)b, n) #define xmlStrcasecmpi(a, b) strcasecmp((char *)a, (char *)b) #endif #define XML_NANO_HTTP_MAX_REDIR 10 #define XML_NANO_HTTP_CHUNK 4096 #define XML_NANO_HTTP_CLOSED 0 #define XML_NANO_HTTP_WRITE 1 #define XML_NANO_HTTP_READ 2 #define XML_NANO_HTTP_NONE 4 typedef struct xmlNanoHTTPCtxt { char *protocol; /* the protocol name */ char *hostname; /* the host name */ int port; /* the port */ char *path; /* the path within the URL */ char *query; /* the query string */ SOCKET fd; /* the file descriptor for the socket */ int state; /* WRITE / READ / CLOSED */ char *out; /* buffer sent (zero terminated) */ char *outptr; /* index within the buffer sent */ char *in; /* the receiving buffer */ char *content; /* the start of the content */ char *inptr; /* the next byte to read from network */ char *inrptr; /* the next byte to give back to the client */ int inlen; /* len of the input buffer */ int last; /* return code for last operation */ int returnValue; /* the protocol return value */ int ContentLength; /* specified content length from HTTP header */ char *contentType; /* the MIME type for the input */ char *location; /* the new URL in case of redirect */ char *authHeader; /* contents of {WWW,Proxy}-Authenticate header */ char *encoding; /* encoding extracted from the contentType */ char *mimeType; /* Mime-Type extracted from the contentType */ #ifdef HAVE_ZLIB_H z_stream *strm; /* Zlib stream object */ int usesGzip; /* "Content-Encoding: gzip" was detected */ #endif } xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr; static int initialized = 0; static char *proxy = NULL; /* the proxy name if any */ static int proxyPort; /* the proxy port if any */ static unsigned int timeout = 60;/* the select() timeout in seconds */ static int xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len ); /** * xmlHTTPErrMemory: * @extra: extra informations * * Handle an out of memory condition */ static void xmlHTTPErrMemory(const char *extra) { __xmlSimpleError(XML_FROM_HTTP, XML_ERR_NO_MEMORY, NULL, NULL, extra); } /** * A portability function */ static int socket_errno(void) { #ifdef _WINSOCKAPI_ return(WSAGetLastError()); #else return(errno); #endif } #ifdef SUPPORT_IP6 static int have_ipv6(void) { int s; s = socket (AF_INET6, SOCK_STREAM, 0); if (s != -1) { close (s); return (1); } return (0); } #endif /** * xmlNanoHTTPInit: * * Initialize the HTTP protocol layer. * Currently it just checks for proxy informations */ void xmlNanoHTTPInit(void) { const char *env; #ifdef _WINSOCKAPI_ WSADATA wsaData; #endif if (initialized) return; #ifdef _WINSOCKAPI_ if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) return; #endif if (proxy == NULL) { proxyPort = 80; env = getenv("no_proxy"); if (env && ((env[0] == '*') && (env[1] == 0))) goto done; env = getenv("http_proxy"); if (env != NULL) { xmlNanoHTTPScanProxy(env); goto done; } env = getenv("HTTP_PROXY"); if (env != NULL) { xmlNanoHTTPScanProxy(env); goto done; } } done: initialized = 1; } /** * xmlNanoHTTPCleanup: * * Cleanup the HTTP protocol layer. */ void xmlNanoHTTPCleanup(void) { if (proxy != NULL) { xmlFree(proxy); proxy = NULL; } #ifdef _WINSOCKAPI_ if (initialized) WSACleanup(); #endif initialized = 0; return; } /** * xmlNanoHTTPScanURL: * @ctxt: an HTTP context * @URL: The URL used to initialize the context * * (Re)Initialize an HTTP context by parsing the URL and finding * the protocol host port and path it indicates. */ static void xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) { xmlURIPtr uri; /* * Clear any existing data from the context */ if (ctxt->protocol != NULL) { xmlFree(ctxt->protocol); ctxt->protocol = NULL; } if (ctxt->hostname != NULL) { xmlFree(ctxt->hostname); ctxt->hostname = NULL; } if (ctxt->path != NULL) { xmlFree(ctxt->path); ctxt->path = NULL; } if (ctxt->query != NULL) { xmlFree(ctxt->query); ctxt->query = NULL; } if (URL == NULL) return; uri = xmlParseURIRaw(URL, 1); if (uri == NULL) return; if ((uri->scheme == NULL) || (uri->server == NULL)) { xmlFreeURI(uri); return; } ctxt->protocol = xmlMemStrdup(uri->scheme); ctxt->hostname = xmlMemStrdup(uri->server); if (uri->path != NULL) ctxt->path = xmlMemStrdup(uri->path); else ctxt->path = xmlMemStrdup("/"); if (uri->query != NULL) ctxt->query = xmlMemStrdup(uri->query); if (uri->port != 0) ctxt->port = uri->port; xmlFreeURI(uri); } /** * xmlNanoHTTPScanProxy: * @URL: The proxy URL used to initialize the proxy context * * (Re)Initialize the HTTP Proxy context by parsing the URL and finding * the protocol host port it indicates. * Should be like http://myproxy/ or http://myproxy:3128/ * A NULL URL cleans up proxy informations. */ void xmlNanoHTTPScanProxy(const char *URL) { xmlURIPtr uri; if (proxy != NULL) { xmlFree(proxy); proxy = NULL; } proxyPort = 0; #ifdef DEBUG_HTTP if (URL == NULL) xmlGenericError(xmlGenericErrorContext, "Removing HTTP proxy info\n"); else xmlGenericError(xmlGenericErrorContext, "Using HTTP proxy %s\n", URL); #endif if (URL == NULL) return; uri = xmlParseURIRaw(URL, 1); if ((uri == NULL) || (uri->scheme == NULL) || (strcmp(uri->scheme, "http")) || (uri->server == NULL)) { __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Syntax Error\n"); if (uri != NULL) xmlFreeURI(uri); return; } proxy = xmlMemStrdup(uri->server); if (uri->port != 0) proxyPort = uri->port; xmlFreeURI(uri); } /** * xmlNanoHTTPNewCtxt: * @URL: The URL used to initialize the context * * Allocate and initialize a new HTTP context. * * Returns an HTTP context or NULL in case of error. */ static xmlNanoHTTPCtxtPtr xmlNanoHTTPNewCtxt(const char *URL) { xmlNanoHTTPCtxtPtr ret; ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt)); if (ret == NULL) { xmlHTTPErrMemory("allocating context"); return(NULL); } memset(ret, 0, sizeof(xmlNanoHTTPCtxt)); ret->port = 80; ret->returnValue = 0; ret->fd = -1; ret->ContentLength = -1; xmlNanoHTTPScanURL(ret, URL); return(ret); } /** * xmlNanoHTTPFreeCtxt: * @ctxt: an HTTP context * * Frees the context after closing the connection. */ static void xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) { if (ctxt == NULL) return; if (ctxt->hostname != NULL) xmlFree(ctxt->hostname); if (ctxt->protocol != NULL) xmlFree(ctxt->protocol); if (ctxt->path != NULL) xmlFree(ctxt->path); if (ctxt->query != NULL) xmlFree(ctxt->query); if (ctxt->out != NULL) xmlFree(ctxt->out); if (ctxt->in != NULL) xmlFree(ctxt->in); if (ctxt->contentType != NULL) xmlFree(ctxt->contentType); if (ctxt->encoding != NULL) xmlFree(ctxt->encoding); if (ctxt->mimeType != NULL) xmlFree(ctxt->mimeType); if (ctxt->location != NULL) xmlFree(ctxt->location); if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader); #ifdef HAVE_ZLIB_H if (ctxt->strm != NULL) { inflateEnd(ctxt->strm); xmlFree(ctxt->strm); } #endif ctxt->state = XML_NANO_HTTP_NONE; if (ctxt->fd >= 0) closesocket(ctxt->fd); ctxt->fd = -1; xmlFree(ctxt); } /** * xmlNanoHTTPSend: * @ctxt: an HTTP context * * Send the input needed to initiate the processing on the server side * Returns number of bytes sent or -1 on error. */ static int xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt, const char * xmt_ptr, int outlen) { int total_sent = 0; if ( (ctxt->state & XML_NANO_HTTP_WRITE) && (xmt_ptr != NULL ) ) { while (total_sent < outlen) { int nsent = send(ctxt->fd, xmt_ptr + total_sent, outlen - total_sent, 0); if (nsent>0) total_sent += nsent; else if ( ( nsent == -1 ) && #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK ( socket_errno( ) != EAGAIN ) && #endif ( socket_errno( ) != EWOULDBLOCK ) ) { __xmlIOErr(XML_FROM_HTTP, 0, "send failed\n"); if ( total_sent == 0 ) total_sent = -1; break; } else { /* ** No data sent ** Since non-blocking sockets are used, wait for ** socket to be writable or default timeout prior ** to retrying. */ struct timeval tv; fd_set wfd; tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO( &wfd ); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4018) #endif FD_SET( ctxt->fd, &wfd ); #ifdef _MSC_VER #pragma warning(pop) #endif (void)select( ctxt->fd + 1, NULL, &wfd, NULL, &tv ); } } } return total_sent; } /** * xmlNanoHTTPRecv: * @ctxt: an HTTP context * * Read information coming from the HTTP connection. * This is a blocking call (but it blocks in select(), not read()). * * Returns the number of byte read or -1 in case of error. */ static int xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt) { fd_set rfd; struct timeval tv; while (ctxt->state & XML_NANO_HTTP_READ) { if (ctxt->in == NULL) { ctxt->in = (char *) xmlMallocAtomic(65000 * sizeof(char)); if (ctxt->in == NULL) { xmlHTTPErrMemory("allocating input"); ctxt->last = -1; return(-1); } ctxt->inlen = 65000; ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in; } if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) { int delta = ctxt->inrptr - ctxt->in; int len = ctxt->inptr - ctxt->inrptr; memmove(ctxt->in, ctxt->inrptr, len); ctxt->inrptr -= delta; ctxt->content -= delta; ctxt->inptr -= delta; } if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) { int d_inptr = ctxt->inptr - ctxt->in; int d_content = ctxt->content - ctxt->in; int d_inrptr = ctxt->inrptr - ctxt->in; char * tmp_ptr = ctxt->in; ctxt->inlen *= 2; ctxt->in = (char *) xmlRealloc(tmp_ptr, ctxt->inlen); if (ctxt->in == NULL) { xmlHTTPErrMemory("allocating input buffer"); xmlFree( tmp_ptr ); ctxt->last = -1; return(-1); } ctxt->inptr = ctxt->in + d_inptr; ctxt->content = ctxt->in + d_content; ctxt->inrptr = ctxt->in + d_inrptr; } ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK, 0); if (ctxt->last > 0) { ctxt->inptr += ctxt->last; return(ctxt->last); } if (ctxt->last == 0) { return(0); } if (ctxt->last == -1) { switch (socket_errno()) { case EINPROGRESS: case EWOULDBLOCK: #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK case EAGAIN: #endif break; case ECONNRESET: case ESHUTDOWN: return ( 0 ); default: __xmlIOErr(XML_FROM_HTTP, 0, "recv failed\n"); return(-1); } } tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO(&rfd); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4018) #endif FD_SET(ctxt->fd, &rfd); #ifdef _MSC_VER #pragma warning(pop) #endif if ( (select(ctxt->fd+1, &rfd, NULL, NULL, &tv)<1) #if defined(EINTR) && (errno != EINTR) #endif ) return(0); } return(0); } /** * xmlNanoHTTPReadLine: * @ctxt: an HTTP context * * Read one line in the HTTP server output, usually for extracting * the HTTP protocol informations from the answer header. * * Returns a newly allocated string with a copy of the line, or NULL * which indicate the end of the input. */ static char * xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) { char buf[4096]; char *bp = buf; int rc; while (bp - buf < 4095) { if (ctxt->inrptr == ctxt->inptr) { if ( (rc = xmlNanoHTTPRecv(ctxt)) == 0) { if (bp == buf) return(NULL); else *bp = 0; return(xmlMemStrdup(buf)); } else if ( rc == -1 ) { return ( NULL ); } } *bp = *ctxt->inrptr++; if (*bp == '\n') { *bp = 0; return(xmlMemStrdup(buf)); } if (*bp != '\r') bp++; } buf[4095] = 0; return(xmlMemStrdup(buf)); } /** * xmlNanoHTTPScanAnswer: * @ctxt: an HTTP context * @line: an HTTP header line * * Try to extract useful informations from the server answer. * We currently parse and process: * - The HTTP revision/ return code * - The Content-Type, Mime-Type and charset used * - The Location for redirect processing. * * Returns -1 in case of failure, the file descriptor number otherwise */ static void xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) { const char *cur = line; if (line == NULL) return; if (!strncmp(line, "HTTP/", 5)) { int version = 0; int ret = 0; cur += 5; while ((*cur >= '0') && (*cur <= '9')) { version *= 10; version += *cur - '0'; cur++; } if (*cur == '.') { cur++; if ((*cur >= '0') && (*cur <= '9')) { version *= 10; version += *cur - '0'; cur++; } while ((*cur >= '0') && (*cur <= '9')) cur++; } else version *= 10; if ((*cur != ' ') && (*cur != '\t')) return; while ((*cur == ' ') || (*cur == '\t')) cur++; if ((*cur < '0') || (*cur > '9')) return; while ((*cur >= '0') && (*cur <= '9')) { ret *= 10; ret += *cur - '0'; cur++; } if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return; ctxt->returnValue = ret; } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Content-Type:", 13)) { const xmlChar *charset, *last, *mime; cur += 13; while ((*cur == ' ') || (*cur == '\t')) cur++; if (ctxt->contentType != NULL) xmlFree(ctxt->contentType); ctxt->contentType = xmlMemStrdup(cur); mime = (const xmlChar *) cur; last = mime; while ((*last != 0) && (*last != ' ') && (*last != '\t') && (*last != ';') && (*last != ',')) last++; if (ctxt->mimeType != NULL) xmlFree(ctxt->mimeType); ctxt->mimeType = (char *) xmlStrndup(mime, last - mime); charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset="); if (charset != NULL) { charset += 8; last = charset; while ((*last != 0) && (*last != ' ') && (*last != '\t') && (*last != ';') && (*last != ',')) last++; if (ctxt->encoding != NULL) xmlFree(ctxt->encoding); ctxt->encoding = (char *) xmlStrndup(charset, last - charset); } } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"ContentType:", 12)) { const xmlChar *charset, *last, *mime; cur += 12; if (ctxt->contentType != NULL) return; while ((*cur == ' ') || (*cur == '\t')) cur++; ctxt->contentType = xmlMemStrdup(cur); mime = (const xmlChar *) cur; last = mime; while ((*last != 0) && (*last != ' ') && (*last != '\t') && (*last != ';') && (*last != ',')) last++; if (ctxt->mimeType != NULL) xmlFree(ctxt->mimeType); ctxt->mimeType = (char *) xmlStrndup(mime, last - mime); charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset="); if (charset != NULL) { charset += 8; last = charset; while ((*last != 0) && (*last != ' ') && (*last != '\t') && (*last != ';') && (*last != ',')) last++; if (ctxt->encoding != NULL) xmlFree(ctxt->encoding); ctxt->encoding = (char *) xmlStrndup(charset, last - charset); } } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Location:", 9)) { cur += 9; while ((*cur == ' ') || (*cur == '\t')) cur++; if (ctxt->location != NULL) xmlFree(ctxt->location); if (*cur == '/') { xmlChar *tmp_http = xmlStrdup(BAD_CAST "http://"); xmlChar *tmp_loc = xmlStrcat(tmp_http, (const xmlChar *) ctxt->hostname); ctxt->location = (char *) xmlStrcat (tmp_loc, (const xmlChar *) cur); } else { ctxt->location = xmlMemStrdup(cur); } } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"WWW-Authenticate:", 17)) { cur += 17; while ((*cur == ' ') || (*cur == '\t')) cur++; if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader); ctxt->authHeader = xmlMemStrdup(cur); } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Proxy-Authenticate:", 19)) { cur += 19; while ((*cur == ' ') || (*cur == '\t')) cur++; if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader); ctxt->authHeader = xmlMemStrdup(cur); #ifdef HAVE_ZLIB_H } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Encoding:", 17) ) { cur += 17; while ((*cur == ' ') || (*cur == '\t')) cur++; if ( !xmlStrncasecmp( BAD_CAST cur, BAD_CAST"gzip", 4) ) { ctxt->usesGzip = 1; ctxt->strm = xmlMalloc(sizeof(z_stream)); if (ctxt->strm != NULL) { ctxt->strm->zalloc = Z_NULL; ctxt->strm->zfree = Z_NULL; ctxt->strm->opaque = Z_NULL; ctxt->strm->avail_in = 0; ctxt->strm->next_in = Z_NULL; inflateInit2( ctxt->strm, 31 ); } } #endif } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Length:", 15) ) { cur += 15; ctxt->ContentLength = strtol( cur, NULL, 10 ); } } /** * xmlNanoHTTPConnectAttempt: * @addr: a socket address structure * * Attempt a connection to the given IP:port endpoint. It forces * non-blocking semantic on the socket, and allow 60 seconds for * the host to answer. * * Returns -1 in case of failure, the file descriptor number otherwise */ static int xmlNanoHTTPConnectAttempt(struct sockaddr *addr) { fd_set wfd; #ifdef _WINSOCKAPI_ fd_set xfd; #endif struct timeval tv; int status; int addrlen; SOCKET s; #ifdef SUPPORT_IP6 if (addr->sa_family == AF_INET6) { s = socket (PF_INET6, SOCK_STREAM, IPPROTO_TCP); addrlen = sizeof (struct sockaddr_in6); } else #endif { s = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); addrlen = sizeof (struct sockaddr_in); } if (s==-1) { #ifdef DEBUG_HTTP perror("socket"); #endif __xmlIOErr(XML_FROM_HTTP, 0, "socket failed\n"); return(-1); } #ifdef _WINSOCKAPI_ { u_long one = 1; status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0; } #else /* _WINSOCKAPI_ */ #if defined(VMS) { int enable = 1; status = ioctl(s, FIONBIO, &enable); } #else /* VMS */ #if defined(__BEOS__) { bool noblock = true; status = setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &noblock, sizeof(noblock)); } #else /* __BEOS__ */ if ((status = fcntl(s, F_GETFL, 0)) != -1) { #ifdef O_NONBLOCK status |= O_NONBLOCK; #else /* O_NONBLOCK */ #ifdef F_NDELAY status |= F_NDELAY; #endif /* F_NDELAY */ #endif /* !O_NONBLOCK */ status = fcntl(s, F_SETFL, status); } if (status < 0) { #ifdef DEBUG_HTTP perror("nonblocking"); #endif __xmlIOErr(XML_FROM_HTTP, 0, "error setting non-blocking IO\n"); closesocket(s); return(-1); } #endif /* !__BEOS__ */ #endif /* !VMS */ #endif /* !_WINSOCKAPI_ */ if (connect (s, addr, addrlen) == -1) { switch (socket_errno()) { case EINPROGRESS: case EWOULDBLOCK: break; default: __xmlIOErr(XML_FROM_HTTP, 0, "error connecting to HTTP server"); closesocket(s); return(-1); } } tv.tv_sec = timeout; tv.tv_usec = 0; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4018) #endif FD_ZERO(&wfd); FD_SET(s, &wfd); #ifdef _WINSOCKAPI_ FD_ZERO(&xfd); FD_SET(s, &xfd); switch(select(s+1, NULL, &wfd, &xfd, &tv)) #else switch(select(s+1, NULL, &wfd, NULL, &tv)) #endif #ifdef _MSC_VER #pragma warning(pop) #endif { case 0: /* Time out */ __xmlIOErr(XML_FROM_HTTP, 0, "Connect attempt timed out"); closesocket(s); return(-1); case -1: /* Ermm.. ?? */ __xmlIOErr(XML_FROM_HTTP, 0, "Connect failed"); closesocket(s); return(-1); } if ( FD_ISSET(s, &wfd) #ifdef _WINSOCKAPI_ || FD_ISSET(s, &xfd) #endif ) { XML_SOCKLEN_T len; len = sizeof(status); #ifdef SO_ERROR if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char*)&status, &len) < 0 ) { /* Solaris error code */ __xmlIOErr(XML_FROM_HTTP, 0, "getsockopt failed\n"); return (-1); } #endif if ( status ) { __xmlIOErr(XML_FROM_HTTP, 0, "Error connecting to remote host"); closesocket(s); errno = status; return (-1); } } else { /* pbm */ __xmlIOErr(XML_FROM_HTTP, 0, "select failed\n"); closesocket(s); return (-1); } return(s); } /** * xmlNanoHTTPConnectHost: * @host: the host name * @port: the port number * * Attempt a connection to the given host:port endpoint. It tries * the multiple IP provided by the DNS if available. * * Returns -1 in case of failure, the file descriptor number otherwise */ static int xmlNanoHTTPConnectHost(const char *host, int port) { struct hostent *h; struct sockaddr *addr = NULL; struct in_addr ia; struct sockaddr_in sockin; #ifdef SUPPORT_IP6 struct in6_addr ia6; struct sockaddr_in6 sockin6; #endif int i; int s; memset (&sockin, 0, sizeof(sockin)); #ifdef SUPPORT_IP6 memset (&sockin6, 0, sizeof(sockin6)); #endif #if !defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && defined(RES_USE_INET6) if (have_ipv6 ()) { if (!(_res.options & RES_INIT)) res_init(); _res.options |= RES_USE_INET6; } #endif #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32) if (have_ipv6 ()) #endif #if defined(HAVE_GETADDRINFO) && (defined(SUPPORT_IP6) || defined(_WIN32)) { int status; struct addrinfo hints, *res, *result; result = NULL; memset (&hints, 0,sizeof(hints)); hints.ai_socktype = SOCK_STREAM; status = getaddrinfo (host, NULL, &hints, &result); if (status) { __xmlIOErr(XML_FROM_HTTP, 0, "getaddrinfo failed\n"); return (-1); } for (res = result; res; res = res->ai_next) { if (res->ai_family == AF_INET) { if (res->ai_addrlen > sizeof(sockin)) { __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n"); freeaddrinfo (result); return (-1); } memcpy (&sockin, res->ai_addr, res->ai_addrlen); sockin.sin_port = htons (port); addr = (struct sockaddr *)&sockin; #ifdef SUPPORT_IP6 } else if (have_ipv6 () && (res->ai_family == AF_INET6)) { if (res->ai_addrlen > sizeof(sockin6)) { __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n"); freeaddrinfo (result); return (-1); } memcpy (&sockin6, res->ai_addr, res->ai_addrlen); sockin6.sin6_port = htons (port); addr = (struct sockaddr *)&sockin6; #endif } else continue; /* for */ s = xmlNanoHTTPConnectAttempt (addr); if (s != -1) { freeaddrinfo (result); return (s); } } if (result) freeaddrinfo (result); } #endif #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32) else #endif #if !defined(HAVE_GETADDRINFO) || !defined(_WIN32) { h = gethostbyname (host); if (h == NULL) { /* * Okay, I got fed up by the non-portability of this error message * extraction code. it work on Linux, if it work on your platform * and one want to enable it, send me the defined(foobar) needed */ #if defined(HAVE_NETDB_H) && defined(HOST_NOT_FOUND) && defined(linux) const char *h_err_txt = ""; switch (h_errno) { case HOST_NOT_FOUND: h_err_txt = "Authoritive host not found"; break; case TRY_AGAIN: h_err_txt = "Non-authoritive host not found or server failure."; break; case NO_RECOVERY: h_err_txt = "Non-recoverable errors: FORMERR, REFUSED, or NOTIMP."; break; case NO_ADDRESS: h_err_txt = "Valid name, no data record of requested type."; break; default: h_err_txt = "No error text defined."; break; } __xmlIOErr(XML_FROM_HTTP, 0, h_err_txt); #else __xmlIOErr(XML_FROM_HTTP, 0, "Failed to resolve host"); #endif return (-1); } for (i = 0; h->h_addr_list[i]; i++) { if (h->h_addrtype == AF_INET) { /* A records (IPv4) */ if ((unsigned int) h->h_length > sizeof(ia)) { __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n"); return (-1); } memcpy (&ia, h->h_addr_list[i], h->h_length); sockin.sin_family = h->h_addrtype; sockin.sin_addr = ia; sockin.sin_port = (u_short)htons ((unsigned short)port); addr = (struct sockaddr *) &sockin; #ifdef SUPPORT_IP6 } else if (have_ipv6 () && (h->h_addrtype == AF_INET6)) { /* AAAA records (IPv6) */ if ((unsigned int) h->h_length > sizeof(ia6)) { __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n"); return (-1); } memcpy (&ia6, h->h_addr_list[i], h->h_length); sockin6.sin6_family = h->h_addrtype; sockin6.sin6_addr = ia6; sockin6.sin6_port = htons (port); addr = (struct sockaddr *) &sockin6; #endif } else break; /* for */ s = xmlNanoHTTPConnectAttempt (addr); if (s != -1) return (s); } } #endif #ifdef DEBUG_HTTP xmlGenericError(xmlGenericErrorContext, "xmlNanoHTTPConnectHost: unable to connect to '%s'.\n", host); #endif return (-1); } /** * xmlNanoHTTPOpen: * @URL: The URL to load * @contentType: if available the Content-Type information will be * returned at that location * * This function try to open a connection to the indicated resource * via HTTP GET. * * Returns NULL in case of failure, otherwise a request handler. * The contentType, if provided must be freed by the caller */ void* xmlNanoHTTPOpen(const char *URL, char **contentType) { if (contentType != NULL) *contentType = NULL; return(xmlNanoHTTPMethod(URL, NULL, NULL, contentType, NULL, 0)); } /** * xmlNanoHTTPOpenRedir: * @URL: The URL to load * @contentType: if available the Content-Type information will be * returned at that location * @redir: if available the redirected URL will be returned * * This function try to open a connection to the indicated resource * via HTTP GET. * * Returns NULL in case of failure, otherwise a request handler. * The contentType, if provided must be freed by the caller */ void* xmlNanoHTTPOpenRedir(const char *URL, char **contentType, char **redir) { if (contentType != NULL) *contentType = NULL; if (redir != NULL) *redir = NULL; return(xmlNanoHTTPMethodRedir(URL, NULL, NULL, contentType, redir, NULL,0)); } /** * xmlNanoHTTPRead: * @ctx: the HTTP context * @dest: a buffer * @len: the buffer length * * This function tries to read @len bytes from the existing HTTP connection * and saves them in @dest. This is a blocking call. * * Returns the number of byte read. 0 is an indication of an end of connection. * -1 indicates a parameter error. */ int xmlNanoHTTPRead(void *ctx, void *dest, int len) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx; #ifdef HAVE_ZLIB_H int bytes_read = 0; int orig_avail_in; int z_ret; #endif if (ctx == NULL) return(-1); if (dest == NULL) return(-1); if (len <= 0) return(0); #ifdef HAVE_ZLIB_H if (ctxt->usesGzip == 1) { if (ctxt->strm == NULL) return(0); ctxt->strm->next_out = dest; ctxt->strm->avail_out = len; do { orig_avail_in = ctxt->strm->avail_in = ctxt->inptr - ctxt->inrptr - bytes_read; ctxt->strm->next_in = BAD_CAST (ctxt->inrptr + bytes_read); z_ret = inflate(ctxt->strm, Z_NO_FLUSH); bytes_read += orig_avail_in - ctxt->strm->avail_in; if (z_ret != Z_OK) break; } while (ctxt->strm->avail_out > 0 && xmlNanoHTTPRecv(ctxt) > 0); ctxt->inrptr += bytes_read; return(len - ctxt->strm->avail_out); } #endif while (ctxt->inptr - ctxt->inrptr < len) { if (xmlNanoHTTPRecv(ctxt) <= 0) break; } if (ctxt->inptr - ctxt->inrptr < len) len = ctxt->inptr - ctxt->inrptr; memcpy(dest, ctxt->inrptr, len); ctxt->inrptr += len; return(len); } /** * xmlNanoHTTPClose: * @ctx: the HTTP context * * This function closes an HTTP context, it ends up the connection and * free all data related to it. */ void xmlNanoHTTPClose(void *ctx) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx; if (ctx == NULL) return; xmlNanoHTTPFreeCtxt(ctxt); } /** * xmlNanoHTTPMethodRedir: * @URL: The URL to load * @method: the HTTP method to use * @input: the input string if any * @contentType: the Content-Type information IN and OUT * @redir: the redirected URL OUT * @headers: the extra headers * @ilen: input length * * This function try to open a connection to the indicated resource * via HTTP using the given @method, adding the given extra headers * and the input buffer for the request content. * * Returns NULL in case of failure, otherwise a request handler. * The contentType, or redir, if provided must be freed by the caller */ void* xmlNanoHTTPMethodRedir(const char *URL, const char *method, const char *input, char **contentType, char **redir, const char *headers, int ilen ) { xmlNanoHTTPCtxtPtr ctxt; char *bp, *p; int blen, ret; int head; int nbRedirects = 0; char *redirURL = NULL; #ifdef DEBUG_HTTP int xmt_bytes; #endif if (URL == NULL) return(NULL); if (method == NULL) method = "GET"; xmlNanoHTTPInit(); retry: if (redirURL == NULL) ctxt = xmlNanoHTTPNewCtxt(URL); else { ctxt = xmlNanoHTTPNewCtxt(redirURL); ctxt->location = xmlMemStrdup(redirURL); } if ( ctxt == NULL ) { return ( NULL ); } if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) { __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Not a valid HTTP URI"); xmlNanoHTTPFreeCtxt(ctxt); if (redirURL != NULL) xmlFree(redirURL); return(NULL); } if (ctxt->hostname == NULL) { __xmlIOErr(XML_FROM_HTTP, XML_HTTP_UNKNOWN_HOST, "Failed to identify host in URI"); xmlNanoHTTPFreeCtxt(ctxt); if (redirURL != NULL) xmlFree(redirURL); return(NULL); } if (proxy) { blen = strlen(ctxt->hostname) * 2 + 16; ret = xmlNanoHTTPConnectHost(proxy, proxyPort); } else { blen = strlen(ctxt->hostname); ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port); } if (ret < 0) { xmlNanoHTTPFreeCtxt(ctxt); if (redirURL != NULL) xmlFree(redirURL); return(NULL); } ctxt->fd = ret; if (input == NULL) ilen = 0; else blen += 36; if (headers != NULL) blen += strlen(headers) + 2; if (contentType && *contentType) blen += strlen(*contentType) + 16; if (ctxt->query != NULL) blen += strlen(ctxt->query) + 1; blen += strlen(method) + strlen(ctxt->path) + 24; #ifdef HAVE_ZLIB_H blen += 23; #endif bp = (char*)xmlMallocAtomic(blen); if ( bp == NULL ) { xmlNanoHTTPFreeCtxt( ctxt ); xmlHTTPErrMemory("allocating header buffer"); return ( NULL ); } p = bp; if (proxy) { if (ctxt->port != 80) { p += snprintf( p, blen - (p - bp), "%s http://%s:%d%s", method, ctxt->hostname, ctxt->port, ctxt->path ); } else p += snprintf( p, blen - (p - bp), "%s http://%s%s", method, ctxt->hostname, ctxt->path); } else p += snprintf( p, blen - (p - bp), "%s %s", method, ctxt->path); if (ctxt->query != NULL) p += snprintf( p, blen - (p - bp), "?%s", ctxt->query); p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s\r\n", ctxt->hostname); #ifdef HAVE_ZLIB_H p += snprintf(p, blen - (p - bp), "Accept-Encoding: gzip\r\n"); #endif if (contentType != NULL && *contentType) p += snprintf(p, blen - (p - bp), "Content-Type: %s\r\n", *contentType); if (headers != NULL) p += snprintf( p, blen - (p - bp), "%s", headers ); if (input != NULL) snprintf(p, blen - (p - bp), "Content-Length: %d\r\n\r\n", ilen ); else snprintf(p, blen - (p - bp), "\r\n"); #ifdef DEBUG_HTTP xmlGenericError(xmlGenericErrorContext, "-> %s%s", proxy? "(Proxy) " : "", bp); if ((blen -= strlen(bp)+1) < 0) xmlGenericError(xmlGenericErrorContext, "ERROR: overflowed buffer by %d bytes\n", -blen); #endif ctxt->outptr = ctxt->out = bp; ctxt->state = XML_NANO_HTTP_WRITE; blen = strlen( ctxt->out ); #ifdef DEBUG_HTTP xmt_bytes = xmlNanoHTTPSend(ctxt, ctxt->out, blen ); if ( xmt_bytes != blen ) xmlGenericError( xmlGenericErrorContext, "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n", xmt_bytes, blen, "bytes of HTTP headers sent to host", ctxt->hostname ); #else xmlNanoHTTPSend(ctxt, ctxt->out, blen ); #endif if ( input != NULL ) { #ifdef DEBUG_HTTP xmt_bytes = xmlNanoHTTPSend( ctxt, input, ilen ); if ( xmt_bytes != ilen ) xmlGenericError( xmlGenericErrorContext, "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n", xmt_bytes, ilen, "bytes of HTTP content sent to host", ctxt->hostname ); #else xmlNanoHTTPSend( ctxt, input, ilen ); #endif } ctxt->state = XML_NANO_HTTP_READ; head = 1; while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) { if (head && (*p == 0)) { head = 0; ctxt->content = ctxt->inrptr; xmlFree(p); break; } xmlNanoHTTPScanAnswer(ctxt, p); #ifdef DEBUG_HTTP xmlGenericError(xmlGenericErrorContext, "<- %s\n", p); #endif xmlFree(p); } if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) && (ctxt->returnValue < 400)) { #ifdef DEBUG_HTTP xmlGenericError(xmlGenericErrorContext, "\nRedirect to: %s\n", ctxt->location); #endif while ( xmlNanoHTTPRecv(ctxt) > 0 ) ; if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) { nbRedirects++; if (redirURL != NULL) xmlFree(redirURL); redirURL = xmlMemStrdup(ctxt->location); xmlNanoHTTPFreeCtxt(ctxt); goto retry; } xmlNanoHTTPFreeCtxt(ctxt); if (redirURL != NULL) xmlFree(redirURL); #ifdef DEBUG_HTTP xmlGenericError(xmlGenericErrorContext, "xmlNanoHTTPMethodRedir: Too many redirects, aborting ...\n"); #endif return(NULL); } if (contentType != NULL) { if (ctxt->contentType != NULL) *contentType = xmlMemStrdup(ctxt->contentType); else *contentType = NULL; } if ((redir != NULL) && (redirURL != NULL)) { *redir = redirURL; } else { if (redirURL != NULL) xmlFree(redirURL); if (redir != NULL) *redir = NULL; } #ifdef DEBUG_HTTP if (ctxt->contentType != NULL) xmlGenericError(xmlGenericErrorContext, "\nCode %d, content-type '%s'\n\n", ctxt->returnValue, ctxt->contentType); else xmlGenericError(xmlGenericErrorContext, "\nCode %d, no content-type\n\n", ctxt->returnValue); #endif return((void *) ctxt); } /** * xmlNanoHTTPMethod: * @URL: The URL to load * @method: the HTTP method to use * @input: the input string if any * @contentType: the Content-Type information IN and OUT * @headers: the extra headers * @ilen: input length * * This function try to open a connection to the indicated resource * via HTTP using the given @method, adding the given extra headers * and the input buffer for the request content. * * Returns NULL in case of failure, otherwise a request handler. * The contentType, if provided must be freed by the caller */ void* xmlNanoHTTPMethod(const char *URL, const char *method, const char *input, char **contentType, const char *headers, int ilen) { return(xmlNanoHTTPMethodRedir(URL, method, input, contentType, NULL, headers, ilen)); } /** * xmlNanoHTTPFetch: * @URL: The URL to load * @filename: the filename where the content should be saved * @contentType: if available the Content-Type information will be * returned at that location * * This function try to fetch the indicated resource via HTTP GET * and save it's content in the file. * * Returns -1 in case of failure, 0 incase of success. The contentType, * if provided must be freed by the caller */ int xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) { void *ctxt = NULL; char *buf = NULL; int fd; int len; if (filename == NULL) return(-1); ctxt = xmlNanoHTTPOpen(URL, contentType); if (ctxt == NULL) return(-1); if (!strcmp(filename, "-")) fd = 0; else { fd = open(filename, O_CREAT | O_WRONLY, 00644); if (fd < 0) { xmlNanoHTTPClose(ctxt); if ((contentType != NULL) && (*contentType != NULL)) { xmlFree(*contentType); *contentType = NULL; } return(-1); } } xmlNanoHTTPFetchContent( ctxt, &buf, &len ); if ( len > 0 ) { write(fd, buf, len); } xmlNanoHTTPClose(ctxt); close(fd); return(0); } #ifdef LIBXML_OUTPUT_ENABLED /** * xmlNanoHTTPSave: * @ctxt: the HTTP context * @filename: the filename where the content should be saved * * This function saves the output of the HTTP transaction to a file * It closes and free the context at the end * * Returns -1 in case of failure, 0 incase of success. */ int xmlNanoHTTPSave(void *ctxt, const char *filename) { char *buf = NULL; int fd; int len; if ((ctxt == NULL) || (filename == NULL)) return(-1); if (!strcmp(filename, "-")) fd = 0; else { fd = open(filename, O_CREAT | O_WRONLY); if (fd < 0) { xmlNanoHTTPClose(ctxt); return(-1); } } xmlNanoHTTPFetchContent( ctxt, &buf, &len ); if ( len > 0 ) { write(fd, buf, len); } xmlNanoHTTPClose(ctxt); close(fd); return(0); } #endif /* LIBXML_OUTPUT_ENABLED */ /** * xmlNanoHTTPReturnCode: * @ctx: the HTTP context * * Get the latest HTTP return code received * * Returns the HTTP return code for the request. */ int xmlNanoHTTPReturnCode(void *ctx) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx; if (ctxt == NULL) return(-1); return(ctxt->returnValue); } /** * xmlNanoHTTPAuthHeader: * @ctx: the HTTP context * * Get the authentication header of an HTTP context * * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate * header. */ const char * xmlNanoHTTPAuthHeader(void *ctx) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx; if (ctxt == NULL) return(NULL); return(ctxt->authHeader); } /** * xmlNanoHTTPContentLength: * @ctx: the HTTP context * * Provides the specified content length from the HTTP header. * * Return the specified content length from the HTTP header. Note that * a value of -1 indicates that the content length element was not included in * the response header. */ int xmlNanoHTTPContentLength( void * ctx ) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx; return ( ( ctxt == NULL ) ? -1 : ctxt->ContentLength ); } /** * xmlNanoHTTPRedir: * @ctx: the HTTP context * * Provides the specified redirection URL if available from the HTTP header. * * Return the specified redirection URL or NULL if not redirected. */ const char * xmlNanoHTTPRedir( void * ctx ) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx; return ( ( ctxt == NULL ) ? NULL : ctxt->location ); } /** * xmlNanoHTTPEncoding: * @ctx: the HTTP context * * Provides the specified encoding if specified in the HTTP headers. * * Return the specified encoding or NULL if not available */ const char * xmlNanoHTTPEncoding( void * ctx ) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx; return ( ( ctxt == NULL ) ? NULL : ctxt->encoding ); } /** * xmlNanoHTTPMimeType: * @ctx: the HTTP context * * Provides the specified Mime-Type if specified in the HTTP headers. * * Return the specified Mime-Type or NULL if not available */ const char * xmlNanoHTTPMimeType( void * ctx ) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx; return ( ( ctxt == NULL ) ? NULL : ctxt->mimeType ); } /** * xmlNanoHTTPFetchContent: * @ctx: the HTTP context * @ptr: pointer to set to the content buffer. * @len: integer pointer to hold the length of the content * * Check if all the content was read * * Returns 0 if all the content was read and available, returns * -1 if received content length was less than specified or an error * occurred. */ static int xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len ) { xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx; int rc = 0; int cur_lgth; int rcvd_lgth; int dummy_int; char * dummy_ptr = NULL; /* Dummy up return input parameters if not provided */ if ( len == NULL ) len = &dummy_int; if ( ptr == NULL ) ptr = &dummy_ptr; /* But can't work without the context pointer */ if ( ( ctxt == NULL ) || ( ctxt->content == NULL ) ) { *len = 0; *ptr = NULL; return ( -1 ); } rcvd_lgth = ctxt->inptr - ctxt->content; while ( (cur_lgth = xmlNanoHTTPRecv( ctxt )) > 0 ) { rcvd_lgth += cur_lgth; if ( (ctxt->ContentLength > 0) && (rcvd_lgth >= ctxt->ContentLength) ) break; } *ptr = ctxt->content; *len = rcvd_lgth; if ( ( ctxt->ContentLength > 0 ) && ( rcvd_lgth < ctxt->ContentLength ) ) rc = -1; else if ( rcvd_lgth == 0 ) rc = -1; return ( rc ); } #ifdef STANDALONE int main(int argc, char **argv) { char *contentType = NULL; if (argv[1] != NULL) { if (argv[2] != NULL) xmlNanoHTTPFetch(argv[1], argv[2], &contentType); else xmlNanoHTTPFetch(argv[1], "-", &contentType); if (contentType != NULL) xmlFree(contentType); } else { xmlGenericError(xmlGenericErrorContext, "%s: minimal HTTP GET implementation\n", argv[0]); xmlGenericError(xmlGenericErrorContext, "\tusage %s [ URL [ filename ] ]\n", argv[0]); } xmlNanoHTTPCleanup(); xmlMemoryDump(); return(0); } #endif /* STANDALONE */ #else /* !LIBXML_HTTP_ENABLED */ #ifdef STANDALONE #include int main(int argc, char **argv) { xmlGenericError(xmlGenericErrorContext, "%s : HTTP support not compiled in\n", argv[0]); return(0); } #endif /* STANDALONE */ #endif /* LIBXML_HTTP_ENABLED */ #define bottom_nanohttp #include "elfgcchack.h" xdmf-2.1.dfsg.1/Utilities/vtklibxml2/xmlschemastypes.c0000644000175000017500000062335411606020250024200 0ustar amckinstryamckinstry/* * schemastypes.c : implementation of the XML Schema Datatypes * definition and validity checking * * See Copyright for the status of this software. * * Daniel Veillard */ #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_SCHEMAS_ENABLED #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_MATH_H #include #endif #ifdef HAVE_FLOAT_H #include #endif #define DEBUG #ifndef LIBXML_XPATH_ENABLED extern double xmlXPathNAN; extern double xmlXPathPINF; extern double xmlXPathNINF; #endif #define TODO \ xmlGenericError(xmlGenericErrorContext, \ "Unimplemented block at %s:%d\n", \ __FILE__, __LINE__); #define XML_SCHEMAS_NAMESPACE_NAME \ (const xmlChar *)"http://www.w3.org/2001/XMLSchema" #define IS_WSP_REPLACE_CH(c) ((((c) == 0x9) || ((c) == 0xa)) || \ ((c) == 0xd)) #define IS_WSP_SPACE_CH(c) ((c) == 0x20) #define IS_WSP_BLANK_CH(c) IS_BLANK_CH(c) /* Date value */ typedef struct _xmlSchemaValDate xmlSchemaValDate; typedef xmlSchemaValDate *xmlSchemaValDatePtr; struct _xmlSchemaValDate { long year; unsigned int mon :4; /* 1 <= mon <= 12 */ unsigned int day :5; /* 1 <= day <= 31 */ unsigned int hour :5; /* 0 <= hour <= 23 */ unsigned int min :6; /* 0 <= min <= 59 */ double sec; unsigned int tz_flag :1; /* is tzo explicitely set? */ signed int tzo :12; /* -1440 <= tzo <= 1440; currently only -840 to +840 are needed */ }; /* Duration value */ typedef struct _xmlSchemaValDuration xmlSchemaValDuration; typedef xmlSchemaValDuration *xmlSchemaValDurationPtr; struct _xmlSchemaValDuration { long mon; /* mon stores years also */ long day; double sec; /* sec stores min and hour also */ }; typedef struct _xmlSchemaValDecimal xmlSchemaValDecimal; typedef xmlSchemaValDecimal *xmlSchemaValDecimalPtr; struct _xmlSchemaValDecimal { /* would use long long but not portable */ unsigned long lo; unsigned long mi; unsigned long hi; unsigned int extra; unsigned int sign:1; unsigned int frac:7; unsigned int total:8; }; typedef struct _xmlSchemaValQName xmlSchemaValQName; typedef xmlSchemaValQName *xmlSchemaValQNamePtr; struct _xmlSchemaValQName { xmlChar *name; xmlChar *uri; }; typedef struct _xmlSchemaValHex xmlSchemaValHex; typedef xmlSchemaValHex *xmlSchemaValHexPtr; struct _xmlSchemaValHex { xmlChar *str; unsigned int total; }; typedef struct _xmlSchemaValBase64 xmlSchemaValBase64; typedef xmlSchemaValBase64 *xmlSchemaValBase64Ptr; struct _xmlSchemaValBase64 { xmlChar *str; unsigned int total; }; struct _xmlSchemaVal { xmlSchemaValType type; struct _xmlSchemaVal *next; union { xmlSchemaValDecimal decimal; xmlSchemaValDate date; xmlSchemaValDuration dur; xmlSchemaValQName qname; xmlSchemaValHex hex; xmlSchemaValBase64 base64; float f; double d; int b; xmlChar *str; } value; }; static int xmlSchemaTypesInitialized = 0; static xmlHashTablePtr xmlSchemaTypesBank = NULL; /* * Basic types */ static xmlSchemaTypePtr xmlSchemaTypeStringDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeAnyTypeDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeAnySimpleTypeDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeDecimalDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeDatetimeDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeDateDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeTimeDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeGYearDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeGYearMonthDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeGDayDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeGMonthDayDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeGMonthDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeDurationDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeFloatDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeBooleanDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeDoubleDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeHexBinaryDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeBase64BinaryDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeAnyURIDef = NULL; /* * Derived types */ static xmlSchemaTypePtr xmlSchemaTypePositiveIntegerDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNonPositiveIntegerDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNegativeIntegerDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNonNegativeIntegerDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeIntegerDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeLongDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeIntDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeShortDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeByteDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeUnsignedLongDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeUnsignedIntDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeUnsignedShortDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeUnsignedByteDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNormStringDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeTokenDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeLanguageDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNameDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeQNameDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNCNameDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeIdDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeIdrefDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeIdrefsDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeEntityDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeEntitiesDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNotationDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNmtokenDef = NULL; static xmlSchemaTypePtr xmlSchemaTypeNmtokensDef = NULL; /************************************************************************ * * * Datatype error handlers * * * ************************************************************************/ /** * xmlSchemaTypeErrMemory: * @extra: extra informations * * Handle an out of memory condition */ static void xmlSchemaTypeErrMemory(xmlNodePtr node, const char *extra) { __xmlSimpleError(XML_FROM_DATATYPE, XML_ERR_NO_MEMORY, node, NULL, extra); } /************************************************************************ * * * Base types support * * * ************************************************************************/ /** * xmlSchemaNewValue: * @type: the value type * * Allocate a new simple type value * * Returns a pointer to the new value or NULL in case of error */ static xmlSchemaValPtr xmlSchemaNewValue(xmlSchemaValType type) { xmlSchemaValPtr value; value = (xmlSchemaValPtr) xmlMalloc(sizeof(xmlSchemaVal)); if (value == NULL) { return(NULL); } memset(value, 0, sizeof(xmlSchemaVal)); value->type = type; return(value); } static xmlSchemaFacetPtr xmlSchemaNewMinLengthFacet(int value) { xmlSchemaFacetPtr ret; ret = xmlSchemaNewFacet(); if (ret == NULL) { return(NULL); } ret->type = XML_SCHEMA_FACET_MINLENGTH; ret->val = xmlSchemaNewValue(XML_SCHEMAS_NNINTEGER); ret->val->value.decimal.lo = value; return (ret); } /* * xmlSchemaInitBasicType: * @name: the type name * @type: the value type associated * * Initialize one primitive built-in type */ static xmlSchemaTypePtr xmlSchemaInitBasicType(const char *name, xmlSchemaValType type, xmlSchemaTypePtr baseType) { xmlSchemaTypePtr ret; ret = (xmlSchemaTypePtr) xmlMalloc(sizeof(xmlSchemaType)); if (ret == NULL) { xmlSchemaTypeErrMemory(NULL, "could not initialize basic types"); return(NULL); } memset(ret, 0, sizeof(xmlSchemaType)); ret->name = (const xmlChar *)name; ret->targetNamespace = XML_SCHEMAS_NAMESPACE_NAME; ret->type = XML_SCHEMA_TYPE_BASIC; ret->baseType = baseType; ret->contentType = XML_SCHEMA_CONTENT_BASIC; /* * Primitive types. */ switch (type) { case XML_SCHEMAS_STRING: case XML_SCHEMAS_DECIMAL: case XML_SCHEMAS_DATE: case XML_SCHEMAS_DATETIME: case XML_SCHEMAS_TIME: case XML_SCHEMAS_GYEAR: case XML_SCHEMAS_GYEARMONTH: case XML_SCHEMAS_GMONTH: case XML_SCHEMAS_GMONTHDAY: case XML_SCHEMAS_GDAY: case XML_SCHEMAS_DURATION: case XML_SCHEMAS_FLOAT: case XML_SCHEMAS_DOUBLE: case XML_SCHEMAS_BOOLEAN: case XML_SCHEMAS_ANYURI: case XML_SCHEMAS_HEXBINARY: case XML_SCHEMAS_BASE64BINARY: case XML_SCHEMAS_QNAME: case XML_SCHEMAS_NOTATION: ret->flags |= XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE; break; default: break; } /* * Set variety. */ switch (type) { case XML_SCHEMAS_ANYTYPE: case XML_SCHEMAS_ANYSIMPLETYPE: break; case XML_SCHEMAS_IDREFS: case XML_SCHEMAS_NMTOKENS: case XML_SCHEMAS_ENTITIES: ret->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST; ret->facets = xmlSchemaNewMinLengthFacet(1); ret->flags |= XML_SCHEMAS_TYPE_HAS_FACETS; break; default: ret->flags |= XML_SCHEMAS_TYPE_VARIETY_ATOMIC; break; } xmlHashAddEntry2(xmlSchemaTypesBank, ret->name, XML_SCHEMAS_NAMESPACE_NAME, ret); ret->builtInType = type; return(ret); } /* * WARNING: Those type reside normally in xmlschemas.c but are * redefined here locally in oder of being able to use them for xs:anyType- * TODO: Remove those definition if we move the types to a header file. * TODO: Always keep those structs up-to-date with the originals. */ #define UNBOUNDED (1 << 30) typedef struct _xmlSchemaTreeItem xmlSchemaTreeItem; typedef xmlSchemaTreeItem *xmlSchemaTreeItemPtr; struct _xmlSchemaTreeItem { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; xmlSchemaTreeItemPtr next; xmlSchemaTreeItemPtr children; }; typedef struct _xmlSchemaParticle xmlSchemaParticle; typedef xmlSchemaParticle *xmlSchemaParticlePtr; struct _xmlSchemaParticle { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; xmlSchemaTreeItemPtr next; xmlSchemaTreeItemPtr children; int minOccurs; int maxOccurs; xmlNodePtr node; }; typedef struct _xmlSchemaModelGroup xmlSchemaModelGroup; typedef xmlSchemaModelGroup *xmlSchemaModelGroupPtr; struct _xmlSchemaModelGroup { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; xmlSchemaTreeItemPtr next; xmlSchemaTreeItemPtr children; xmlNodePtr node; }; static xmlSchemaParticlePtr xmlSchemaAddParticle(void) { xmlSchemaParticlePtr ret = NULL; ret = (xmlSchemaParticlePtr) xmlMalloc(sizeof(xmlSchemaParticle)); if (ret == NULL) { xmlSchemaTypeErrMemory(NULL, "allocating particle component"); return (NULL); } memset(ret, 0, sizeof(xmlSchemaParticle)); ret->type = XML_SCHEMA_TYPE_PARTICLE; ret->minOccurs = 1; ret->maxOccurs = 1; return (ret); } /* * xmlSchemaInitTypes: * * Initialize the default XML Schemas type library */ void xmlSchemaInitTypes(void) { if (xmlSchemaTypesInitialized != 0) return; xmlSchemaTypesBank = xmlHashCreate(40); /* * 3.4.7 Built-in Complex Type Definition */ xmlSchemaTypeAnyTypeDef = xmlSchemaInitBasicType("anyType", XML_SCHEMAS_ANYTYPE, NULL); xmlSchemaTypeAnyTypeDef->baseType = xmlSchemaTypeAnyTypeDef; xmlSchemaTypeAnyTypeDef->contentType = XML_SCHEMA_CONTENT_MIXED; /* * Init the content type. */ xmlSchemaTypeAnyTypeDef->contentType = XML_SCHEMA_CONTENT_MIXED; { xmlSchemaParticlePtr particle; xmlSchemaModelGroupPtr sequence; xmlSchemaWildcardPtr wild; /* First particle. */ particle = xmlSchemaAddParticle(); if (particle == NULL) return; xmlSchemaTypeAnyTypeDef->subtypes = (xmlSchemaTypePtr) particle; /* Sequence model group. */ sequence = (xmlSchemaModelGroupPtr) xmlMalloc(sizeof(xmlSchemaModelGroup)); if (sequence == NULL) { xmlSchemaTypeErrMemory(NULL, "allocating model group component"); return; } memset(sequence, 0, sizeof(xmlSchemaModelGroup)); sequence->type = XML_SCHEMA_TYPE_SEQUENCE; particle->children = (xmlSchemaTreeItemPtr) sequence; /* Second particle. */ particle = xmlSchemaAddParticle(); if (particle == NULL) return; particle->minOccurs = 0; particle->maxOccurs = UNBOUNDED; sequence->children = (xmlSchemaTreeItemPtr) particle; /* The wildcard */ wild = (xmlSchemaWildcardPtr) xmlMalloc(sizeof(xmlSchemaWildcard)); if (wild == NULL) { xmlSchemaTypeErrMemory(NULL, "allocating wildcard component"); return; } memset(wild, 0, sizeof(xmlSchemaWildcard)); wild->type = XML_SCHEMA_TYPE_ANY; wild->any = 1; wild->processContents = XML_SCHEMAS_ANY_LAX; particle->children = (xmlSchemaTreeItemPtr) wild; /* * Create the attribute wildcard. */ wild = (xmlSchemaWildcardPtr) xmlMalloc(sizeof(xmlSchemaWildcard)); if (wild == NULL) { xmlSchemaTypeErrMemory(NULL, "could not create an attribute " "wildcard on anyType"); return; } memset(wild, 0, sizeof(xmlSchemaWildcard)); wild->any = 1; wild->processContents = XML_SCHEMAS_ANY_LAX; xmlSchemaTypeAnyTypeDef->attributeWildcard = wild; } xmlSchemaTypeAnySimpleTypeDef = xmlSchemaInitBasicType("anySimpleType", XML_SCHEMAS_ANYSIMPLETYPE, xmlSchemaTypeAnyTypeDef); /* * primitive datatypes */ xmlSchemaTypeStringDef = xmlSchemaInitBasicType("string", XML_SCHEMAS_STRING, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeDecimalDef = xmlSchemaInitBasicType("decimal", XML_SCHEMAS_DECIMAL, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeDateDef = xmlSchemaInitBasicType("date", XML_SCHEMAS_DATE, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeDatetimeDef = xmlSchemaInitBasicType("dateTime", XML_SCHEMAS_DATETIME, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeTimeDef = xmlSchemaInitBasicType("time", XML_SCHEMAS_TIME, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeGYearDef = xmlSchemaInitBasicType("gYear", XML_SCHEMAS_GYEAR, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeGYearMonthDef = xmlSchemaInitBasicType("gYearMonth", XML_SCHEMAS_GYEARMONTH, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeGMonthDef = xmlSchemaInitBasicType("gMonth", XML_SCHEMAS_GMONTH, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeGMonthDayDef = xmlSchemaInitBasicType("gMonthDay", XML_SCHEMAS_GMONTHDAY, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeGDayDef = xmlSchemaInitBasicType("gDay", XML_SCHEMAS_GDAY, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeDurationDef = xmlSchemaInitBasicType("duration", XML_SCHEMAS_DURATION, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeFloatDef = xmlSchemaInitBasicType("float", XML_SCHEMAS_FLOAT, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeDoubleDef = xmlSchemaInitBasicType("double", XML_SCHEMAS_DOUBLE, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeBooleanDef = xmlSchemaInitBasicType("boolean", XML_SCHEMAS_BOOLEAN, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeAnyURIDef = xmlSchemaInitBasicType("anyURI", XML_SCHEMAS_ANYURI, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeHexBinaryDef = xmlSchemaInitBasicType("hexBinary", XML_SCHEMAS_HEXBINARY, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeBase64BinaryDef = xmlSchemaInitBasicType("base64Binary", XML_SCHEMAS_BASE64BINARY, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeNotationDef = xmlSchemaInitBasicType("NOTATION", XML_SCHEMAS_NOTATION, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeQNameDef = xmlSchemaInitBasicType("QName", XML_SCHEMAS_QNAME, xmlSchemaTypeAnySimpleTypeDef); /* * derived datatypes */ xmlSchemaTypeIntegerDef = xmlSchemaInitBasicType("integer", XML_SCHEMAS_INTEGER, xmlSchemaTypeDecimalDef); xmlSchemaTypeNonPositiveIntegerDef = xmlSchemaInitBasicType("nonPositiveInteger", XML_SCHEMAS_NPINTEGER, xmlSchemaTypeIntegerDef); xmlSchemaTypeNegativeIntegerDef = xmlSchemaInitBasicType("negativeInteger", XML_SCHEMAS_NINTEGER, xmlSchemaTypeNonPositiveIntegerDef); xmlSchemaTypeLongDef = xmlSchemaInitBasicType("long", XML_SCHEMAS_LONG, xmlSchemaTypeIntegerDef); xmlSchemaTypeIntDef = xmlSchemaInitBasicType("int", XML_SCHEMAS_INT, xmlSchemaTypeLongDef); xmlSchemaTypeShortDef = xmlSchemaInitBasicType("short", XML_SCHEMAS_SHORT, xmlSchemaTypeIntDef); xmlSchemaTypeByteDef = xmlSchemaInitBasicType("byte", XML_SCHEMAS_BYTE, xmlSchemaTypeShortDef); xmlSchemaTypeNonNegativeIntegerDef = xmlSchemaInitBasicType("nonNegativeInteger", XML_SCHEMAS_NNINTEGER, xmlSchemaTypeIntegerDef); xmlSchemaTypeUnsignedLongDef = xmlSchemaInitBasicType("unsignedLong", XML_SCHEMAS_ULONG, xmlSchemaTypeNonNegativeIntegerDef); xmlSchemaTypeUnsignedIntDef = xmlSchemaInitBasicType("unsignedInt", XML_SCHEMAS_UINT, xmlSchemaTypeUnsignedLongDef); xmlSchemaTypeUnsignedShortDef = xmlSchemaInitBasicType("unsignedShort", XML_SCHEMAS_USHORT, xmlSchemaTypeUnsignedIntDef); xmlSchemaTypeUnsignedByteDef = xmlSchemaInitBasicType("unsignedByte", XML_SCHEMAS_UBYTE, xmlSchemaTypeUnsignedShortDef); xmlSchemaTypePositiveIntegerDef = xmlSchemaInitBasicType("positiveInteger", XML_SCHEMAS_PINTEGER, xmlSchemaTypeNonNegativeIntegerDef); xmlSchemaTypeNormStringDef = xmlSchemaInitBasicType("normalizedString", XML_SCHEMAS_NORMSTRING, xmlSchemaTypeStringDef); xmlSchemaTypeTokenDef = xmlSchemaInitBasicType("token", XML_SCHEMAS_TOKEN, xmlSchemaTypeNormStringDef); xmlSchemaTypeLanguageDef = xmlSchemaInitBasicType("language", XML_SCHEMAS_LANGUAGE, xmlSchemaTypeTokenDef); xmlSchemaTypeNameDef = xmlSchemaInitBasicType("Name", XML_SCHEMAS_NAME, xmlSchemaTypeTokenDef); xmlSchemaTypeNmtokenDef = xmlSchemaInitBasicType("NMTOKEN", XML_SCHEMAS_NMTOKEN, xmlSchemaTypeTokenDef); xmlSchemaTypeNCNameDef = xmlSchemaInitBasicType("NCName", XML_SCHEMAS_NCNAME, xmlSchemaTypeNameDef); xmlSchemaTypeIdDef = xmlSchemaInitBasicType("ID", XML_SCHEMAS_ID, xmlSchemaTypeNCNameDef); xmlSchemaTypeIdrefDef = xmlSchemaInitBasicType("IDREF", XML_SCHEMAS_IDREF, xmlSchemaTypeNCNameDef); xmlSchemaTypeEntityDef = xmlSchemaInitBasicType("ENTITY", XML_SCHEMAS_ENTITY, xmlSchemaTypeNCNameDef); /* * Derived list types. */ /* ENTITIES */ xmlSchemaTypeEntitiesDef = xmlSchemaInitBasicType("ENTITIES", XML_SCHEMAS_ENTITIES, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeEntitiesDef->subtypes = xmlSchemaTypeEntityDef; /* IDREFS */ xmlSchemaTypeIdrefsDef = xmlSchemaInitBasicType("IDREFS", XML_SCHEMAS_IDREFS, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeIdrefsDef->subtypes = xmlSchemaTypeIdrefDef; /* NMTOKENS */ xmlSchemaTypeNmtokensDef = xmlSchemaInitBasicType("NMTOKENS", XML_SCHEMAS_NMTOKENS, xmlSchemaTypeAnySimpleTypeDef); xmlSchemaTypeNmtokensDef->subtypes = xmlSchemaTypeNmtokenDef; xmlSchemaTypesInitialized = 1; } /** * xmlSchemaCleanupTypes: * * Cleanup the default XML Schemas type library */ void xmlSchemaCleanupTypes(void) { if (xmlSchemaTypesInitialized == 0) return; /* * Free xs:anyType. */ { xmlSchemaParticlePtr particle; /* Attribute wildcard. */ xmlSchemaFreeWildcard(xmlSchemaTypeAnyTypeDef->attributeWildcard); /* Content type. */ particle = (xmlSchemaParticlePtr) xmlSchemaTypeAnyTypeDef->subtypes; /* Wildcard. */ xmlSchemaFreeWildcard((xmlSchemaWildcardPtr) particle->children->children->children); xmlFree((xmlSchemaParticlePtr) particle->children->children); /* Sequence model group. */ xmlFree((xmlSchemaModelGroupPtr) particle->children); xmlFree((xmlSchemaParticlePtr) particle); xmlSchemaTypeAnyTypeDef->subtypes = NULL; } xmlHashFree(xmlSchemaTypesBank, (xmlHashDeallocator) xmlSchemaFreeType); xmlSchemaTypesInitialized = 0; } /** * xmlSchemaIsBuiltInTypeFacet: * @type: the built-in type * @facetType: the facet type * * Evaluates if a specific facet can be * used in conjunction with a type. * * Returns 1 if the facet can be used with the given built-in type, * 0 otherwise and -1 in case the type is not a built-in type. */ int xmlSchemaIsBuiltInTypeFacet(xmlSchemaTypePtr type, int facetType) { if (type == NULL) return (-1); if (type->type != XML_SCHEMA_TYPE_BASIC) return (-1); switch (type->builtInType) { case XML_SCHEMAS_BOOLEAN: if ((facetType == XML_SCHEMA_FACET_PATTERN) || (facetType == XML_SCHEMA_FACET_WHITESPACE)) return (1); else return (0); case XML_SCHEMAS_STRING: case XML_SCHEMAS_NOTATION: case XML_SCHEMAS_QNAME: case XML_SCHEMAS_ANYURI: case XML_SCHEMAS_BASE64BINARY: case XML_SCHEMAS_HEXBINARY: if ((facetType == XML_SCHEMA_FACET_LENGTH) || (facetType == XML_SCHEMA_FACET_MINLENGTH) || (facetType == XML_SCHEMA_FACET_MAXLENGTH) || (facetType == XML_SCHEMA_FACET_PATTERN) || (facetType == XML_SCHEMA_FACET_ENUMERATION) || (facetType == XML_SCHEMA_FACET_WHITESPACE)) return (1); else return (0); case XML_SCHEMAS_DECIMAL: if ((facetType == XML_SCHEMA_FACET_TOTALDIGITS) || (facetType == XML_SCHEMA_FACET_FRACTIONDIGITS) || (facetType == XML_SCHEMA_FACET_PATTERN) || (facetType == XML_SCHEMA_FACET_WHITESPACE) || (facetType == XML_SCHEMA_FACET_ENUMERATION) || (facetType == XML_SCHEMA_FACET_MAXINCLUSIVE) || (facetType == XML_SCHEMA_FACET_MAXEXCLUSIVE) || (facetType == XML_SCHEMA_FACET_MININCLUSIVE) || (facetType == XML_SCHEMA_FACET_MINEXCLUSIVE)) return (1); else return (0); case XML_SCHEMAS_TIME: case XML_SCHEMAS_GDAY: case XML_SCHEMAS_GMONTH: case XML_SCHEMAS_GMONTHDAY: case XML_SCHEMAS_GYEAR: case XML_SCHEMAS_GYEARMONTH: case XML_SCHEMAS_DATE: case XML_SCHEMAS_DATETIME: case XML_SCHEMAS_DURATION: case XML_SCHEMAS_FLOAT: case XML_SCHEMAS_DOUBLE: if ((facetType == XML_SCHEMA_FACET_PATTERN) || (facetType == XML_SCHEMA_FACET_ENUMERATION) || (facetType == XML_SCHEMA_FACET_WHITESPACE) || (facetType == XML_SCHEMA_FACET_MAXINCLUSIVE) || (facetType == XML_SCHEMA_FACET_MAXEXCLUSIVE) || (facetType == XML_SCHEMA_FACET_MININCLUSIVE) || (facetType == XML_SCHEMA_FACET_MINEXCLUSIVE)) return (1); else return (0); default: break; } return (0); } /** * xmlSchemaGetBuiltInType: * @type: the type of the built in type * * Gives you the type struct for a built-in * type by its type id. * * Returns the type if found, NULL otherwise. */ xmlSchemaTypePtr xmlSchemaGetBuiltInType(xmlSchemaValType type) { if (xmlSchemaTypesInitialized == 0) xmlSchemaInitTypes(); switch (type) { case XML_SCHEMAS_ANYSIMPLETYPE: return (xmlSchemaTypeAnySimpleTypeDef); case XML_SCHEMAS_STRING: return (xmlSchemaTypeStringDef); case XML_SCHEMAS_NORMSTRING: return (xmlSchemaTypeNormStringDef); case XML_SCHEMAS_DECIMAL: return (xmlSchemaTypeDecimalDef); case XML_SCHEMAS_TIME: return (xmlSchemaTypeTimeDef); case XML_SCHEMAS_GDAY: return (xmlSchemaTypeGDayDef); case XML_SCHEMAS_GMONTH: return (xmlSchemaTypeGMonthDef); case XML_SCHEMAS_GMONTHDAY: return (xmlSchemaTypeGMonthDayDef); case XML_SCHEMAS_GYEAR: return (xmlSchemaTypeGYearDef); case XML_SCHEMAS_GYEARMONTH: return (xmlSchemaTypeGYearMonthDef); case XML_SCHEMAS_DATE: return (xmlSchemaTypeDateDef); case XML_SCHEMAS_DATETIME: return (xmlSchemaTypeDatetimeDef); case XML_SCHEMAS_DURATION: return (xmlSchemaTypeDurationDef); case XML_SCHEMAS_FLOAT: return (xmlSchemaTypeFloatDef); case XML_SCHEMAS_DOUBLE: return (xmlSchemaTypeDoubleDef); case XML_SCHEMAS_BOOLEAN: return (xmlSchemaTypeBooleanDef); case XML_SCHEMAS_TOKEN: return (xmlSchemaTypeTokenDef); case XML_SCHEMAS_LANGUAGE: return (xmlSchemaTypeLanguageDef); case XML_SCHEMAS_NMTOKEN: return (xmlSchemaTypeNmtokenDef); case XML_SCHEMAS_NMTOKENS: return (xmlSchemaTypeNmtokensDef); case XML_SCHEMAS_NAME: return (xmlSchemaTypeNameDef); case XML_SCHEMAS_QNAME: return (xmlSchemaTypeQNameDef); case XML_SCHEMAS_NCNAME: return (xmlSchemaTypeNCNameDef); case XML_SCHEMAS_ID: return (xmlSchemaTypeIdDef); case XML_SCHEMAS_IDREF: return (xmlSchemaTypeIdrefDef); case XML_SCHEMAS_IDREFS: return (xmlSchemaTypeIdrefsDef); case XML_SCHEMAS_ENTITY: return (xmlSchemaTypeEntityDef); case XML_SCHEMAS_ENTITIES: return (xmlSchemaTypeEntitiesDef); case XML_SCHEMAS_NOTATION: return (xmlSchemaTypeNotationDef); case XML_SCHEMAS_ANYURI: return (xmlSchemaTypeAnyURIDef); case XML_SCHEMAS_INTEGER: return (xmlSchemaTypeIntegerDef); case XML_SCHEMAS_NPINTEGER: return (xmlSchemaTypeNonPositiveIntegerDef); case XML_SCHEMAS_NINTEGER: return (xmlSchemaTypeNegativeIntegerDef); case XML_SCHEMAS_NNINTEGER: return (xmlSchemaTypeNonNegativeIntegerDef); case XML_SCHEMAS_PINTEGER: return (xmlSchemaTypePositiveIntegerDef); case XML_SCHEMAS_INT: return (xmlSchemaTypeIntDef); case XML_SCHEMAS_UINT: return (xmlSchemaTypeUnsignedIntDef); case XML_SCHEMAS_LONG: return (xmlSchemaTypeLongDef); case XML_SCHEMAS_ULONG: return (xmlSchemaTypeUnsignedLongDef); case XML_SCHEMAS_SHORT: return (xmlSchemaTypeShortDef); case XML_SCHEMAS_USHORT: return (xmlSchemaTypeUnsignedShortDef); case XML_SCHEMAS_BYTE: return (xmlSchemaTypeByteDef); case XML_SCHEMAS_UBYTE: return (xmlSchemaTypeUnsignedByteDef); case XML_SCHEMAS_HEXBINARY: return (xmlSchemaTypeHexBinaryDef); case XML_SCHEMAS_BASE64BINARY: return (xmlSchemaTypeBase64BinaryDef); case XML_SCHEMAS_ANYTYPE: return (xmlSchemaTypeAnyTypeDef); default: return (NULL); } } /** * xmlSchemaValueAppend: * @prev: the value * @cur: the value to be appended * * Appends a next sibling to a list of computed values. * * Returns 0 if succeeded and -1 on API errors. */ int xmlSchemaValueAppend(xmlSchemaValPtr prev, xmlSchemaValPtr cur) { if ((prev == NULL) || (cur == NULL)) return (-1); prev->next = cur; return (0); } /** * xmlSchemaValueGetNext: * @cur: the value * * Accessor for the next sibling of a list of computed values. * * Returns the next value or NULL if there was none, or on * API errors. */ xmlSchemaValPtr xmlSchemaValueGetNext(xmlSchemaValPtr cur) { if (cur == NULL) return (NULL); return (cur->next); } /** * xmlSchemaValueGetAsString: * @val: the value * * Accessor for the string value of a computed value. * * Returns the string value or NULL if there was none, or on * API errors. */ const xmlChar * xmlSchemaValueGetAsString(xmlSchemaValPtr val) { if (val == NULL) return (NULL); switch (val->type) { case XML_SCHEMAS_STRING: case XML_SCHEMAS_NORMSTRING: case XML_SCHEMAS_ANYSIMPLETYPE: case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: case XML_SCHEMAS_NMTOKEN: case XML_SCHEMAS_NAME: case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_ID: case XML_SCHEMAS_IDREF: case XML_SCHEMAS_ENTITY: case XML_SCHEMAS_ANYURI: return (BAD_CAST val->value.str); default: break; } return (NULL); } /** * xmlSchemaValueGetAsBoolean: * @val: the value * * Accessor for the boolean value of a computed value. * * Returns 1 if true and 0 if false, or in case of an error. Hmm. */ int xmlSchemaValueGetAsBoolean(xmlSchemaValPtr val) { if ((val == NULL) || (val->type != XML_SCHEMAS_BOOLEAN)) return (0); return (val->value.b); } /** * xmlSchemaNewStringValue: * @type: the value type * @value: the value * * Allocate a new simple type value. The type can be * of XML_SCHEMAS_STRING. * WARNING: This one is intended to be expanded for other * string based types. We need this for anySimpleType as well. * The given value is consumed and freed with the struct. * * Returns a pointer to the new value or NULL in case of error */ xmlSchemaValPtr xmlSchemaNewStringValue(xmlSchemaValType type, const xmlChar *value) { xmlSchemaValPtr val; if (type != XML_SCHEMAS_STRING) return(NULL); val = (xmlSchemaValPtr) xmlMalloc(sizeof(xmlSchemaVal)); if (val == NULL) { return(NULL); } memset(val, 0, sizeof(xmlSchemaVal)); val->type = type; val->value.str = (xmlChar *) value; return(val); } /** * xmlSchemaNewNOTATIONValue: * @name: the notation name * @ns: the notation namespace name or NULL * * Allocate a new NOTATION value. * The given values are consumed and freed with the struct. * * Returns a pointer to the new value or NULL in case of error */ xmlSchemaValPtr xmlSchemaNewNOTATIONValue(const xmlChar *name, const xmlChar *ns) { xmlSchemaValPtr val; val = xmlSchemaNewValue(XML_SCHEMAS_NOTATION); if (val == NULL) return (NULL); val->value.qname.name = (xmlChar *)name; if (ns != NULL) val->value.qname.uri = (xmlChar *)ns; return(val); } /** * xmlSchemaNewQNameValue: * @namespaceName: the namespace name * @localName: the local name * * Allocate a new QName value. * The given values are consumed and freed with the struct. * * Returns a pointer to the new value or NULL in case of an error. */ xmlSchemaValPtr xmlSchemaNewQNameValue(const xmlChar *namespaceName, const xmlChar *localName) { xmlSchemaValPtr val; val = xmlSchemaNewValue(XML_SCHEMAS_QNAME); if (val == NULL) return (NULL); val->value.qname.name = (xmlChar *) localName; val->value.qname.uri = (xmlChar *) namespaceName; return(val); } /** * xmlSchemaFreeValue: * @value: the value to free * * Cleanup the default XML Schemas type library */ void xmlSchemaFreeValue(xmlSchemaValPtr value) { xmlSchemaValPtr prev; while (value != NULL) { switch (value->type) { case XML_SCHEMAS_STRING: case XML_SCHEMAS_NORMSTRING: case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: case XML_SCHEMAS_NMTOKEN: case XML_SCHEMAS_NMTOKENS: case XML_SCHEMAS_NAME: case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_ID: case XML_SCHEMAS_IDREF: case XML_SCHEMAS_IDREFS: case XML_SCHEMAS_ENTITY: case XML_SCHEMAS_ENTITIES: case XML_SCHEMAS_ANYURI: case XML_SCHEMAS_ANYSIMPLETYPE: if (value->value.str != NULL) xmlFree(value->value.str); break; case XML_SCHEMAS_NOTATION: case XML_SCHEMAS_QNAME: if (value->value.qname.uri != NULL) xmlFree(value->value.qname.uri); if (value->value.qname.name != NULL) xmlFree(value->value.qname.name); break; case XML_SCHEMAS_HEXBINARY: if (value->value.hex.str != NULL) xmlFree(value->value.hex.str); break; case XML_SCHEMAS_BASE64BINARY: if (value->value.base64.str != NULL) xmlFree(value->value.base64.str); break; default: break; } prev = value; value = value->next; xmlFree(prev); } } /** * xmlSchemaGetPredefinedType: * @name: the type name * @ns: the URI of the namespace usually "http://www.w3.org/2001/XMLSchema" * * Lookup a type in the default XML Schemas type library * * Returns the type if found, NULL otherwise */ xmlSchemaTypePtr xmlSchemaGetPredefinedType(const xmlChar *name, const xmlChar *ns) { if (xmlSchemaTypesInitialized == 0) xmlSchemaInitTypes(); if (name == NULL) return(NULL); return((xmlSchemaTypePtr) xmlHashLookup2(xmlSchemaTypesBank, name, ns)); } /** * xmlSchemaGetBuiltInListSimpleTypeItemType: * @type: the built-in simple type. * * Lookup function * * Returns the item type of @type as defined by the built-in datatype * hierarchy of XML Schema Part 2: Datatypes, or NULL in case of an error. */ xmlSchemaTypePtr xmlSchemaGetBuiltInListSimpleTypeItemType(xmlSchemaTypePtr type) { if ((type == NULL) || (type->type != XML_SCHEMA_TYPE_BASIC)) return (NULL); switch (type->builtInType) { case XML_SCHEMAS_NMTOKENS: return (xmlSchemaTypeNmtokenDef ); case XML_SCHEMAS_IDREFS: return (xmlSchemaTypeIdrefDef); case XML_SCHEMAS_ENTITIES: return (xmlSchemaTypeEntityDef); default: return (NULL); } } /**************************************************************** * * * Convenience macros and functions * * * ****************************************************************/ #define IS_TZO_CHAR(c) \ ((c == 0) || (c == 'Z') || (c == '+') || (c == '-')) #define VALID_YEAR(yr) (yr != 0) #define VALID_MONTH(mon) ((mon >= 1) && (mon <= 12)) /* VALID_DAY should only be used when month is unknown */ #define VALID_DAY(day) ((day >= 1) && (day <= 31)) #define VALID_HOUR(hr) ((hr >= 0) && (hr <= 23)) #define VALID_MIN(min) ((min >= 0) && (min <= 59)) #define VALID_SEC(sec) ((sec >= 0) && (sec < 60)) #define VALID_TZO(tzo) ((tzo > -840) && (tzo < 840)) #define IS_LEAP(y) \ (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) static const unsigned int daysInMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static const unsigned int daysInMonthLeap[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #define MAX_DAYINMONTH(yr,mon) \ (IS_LEAP(yr) ? daysInMonthLeap[mon - 1] : daysInMonth[mon - 1]) #define VALID_MDAY(dt) \ (IS_LEAP(dt->year) ? \ (dt->day <= daysInMonthLeap[dt->mon - 1]) : \ (dt->day <= daysInMonth[dt->mon - 1])) #define VALID_DATE(dt) \ (VALID_YEAR(dt->year) && VALID_MONTH(dt->mon) && VALID_MDAY(dt)) #define VALID_TIME(dt) \ (VALID_HOUR(dt->hour) && VALID_MIN(dt->min) && \ VALID_SEC(dt->sec) && VALID_TZO(dt->tzo)) #define VALID_DATETIME(dt) \ (VALID_DATE(dt) && VALID_TIME(dt)) #define SECS_PER_MIN (60) #define SECS_PER_HOUR (60 * SECS_PER_MIN) #define SECS_PER_DAY (24 * SECS_PER_HOUR) static const long dayInYearByMonth[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; static const long dayInLeapYearByMonth[12] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }; #define DAY_IN_YEAR(day, month, year) \ ((IS_LEAP(year) ? \ dayInLeapYearByMonth[month - 1] : \ dayInYearByMonth[month - 1]) + day) #ifdef DEBUG #define DEBUG_DATE(dt) \ xmlGenericError(xmlGenericErrorContext, \ "type=%o %04ld-%02u-%02uT%02u:%02u:%03f", \ dt->type,dt->value.date.year,dt->value.date.mon, \ dt->value.date.day,dt->value.date.hour,dt->value.date.min, \ dt->value.date.sec); \ if (dt->value.date.tz_flag) \ if (dt->value.date.tzo != 0) \ xmlGenericError(xmlGenericErrorContext, \ "%+05d\n",dt->value.date.tzo); \ else \ xmlGenericError(xmlGenericErrorContext, "Z\n"); \ else \ xmlGenericError(xmlGenericErrorContext,"\n") #else #define DEBUG_DATE(dt) #endif /** * _xmlSchemaParseGYear: * @dt: pointer to a date structure * @str: pointer to the string to analyze * * Parses a xs:gYear without time zone and fills in the appropriate * field of the @dt structure. @str is updated to point just after the * xs:gYear. It is supposed that @dt->year is big enough to contain * the year. * * Returns 0 or the error code */ static int _xmlSchemaParseGYear (xmlSchemaValDatePtr dt, const xmlChar **str) { const xmlChar *cur = *str, *firstChar; int isneg = 0, digcnt = 0; if (((*cur < '0') || (*cur > '9')) && (*cur != '-') && (*cur != '+')) return -1; if (*cur == '-') { isneg = 1; cur++; } firstChar = cur; while ((*cur >= '0') && (*cur <= '9')) { dt->year = dt->year * 10 + (*cur - '0'); cur++; digcnt++; } /* year must be at least 4 digits (CCYY); over 4 * digits cannot have a leading zero. */ if ((digcnt < 4) || ((digcnt > 4) && (*firstChar == '0'))) return 1; if (isneg) dt->year = - dt->year; if (!VALID_YEAR(dt->year)) return 2; *str = cur; return 0; } /** * PARSE_2_DIGITS: * @num: the integer to fill in * @cur: an #xmlChar * * @invalid: an integer * * Parses a 2-digits integer and updates @num with the value. @cur is * updated to point just after the integer. * In case of error, @invalid is set to %TRUE, values of @num and * @cur are undefined. */ #define PARSE_2_DIGITS(num, cur, invalid) \ if ((cur[0] < '0') || (cur[0] > '9') || \ (cur[1] < '0') || (cur[1] > '9')) \ invalid = 1; \ else \ num = (cur[0] - '0') * 10 + (cur[1] - '0'); \ cur += 2; /** * PARSE_FLOAT: * @num: the double to fill in * @cur: an #xmlChar * * @invalid: an integer * * Parses a float and updates @num with the value. @cur is * updated to point just after the float. The float must have a * 2-digits integer part and may or may not have a decimal part. * In case of error, @invalid is set to %TRUE, values of @num and * @cur are undefined. */ #define PARSE_FLOAT(num, cur, invalid) \ PARSE_2_DIGITS(num, cur, invalid); \ if (!invalid && (*cur == '.')) { \ double mult = 1; \ cur++; \ if ((*cur < '0') || (*cur > '9')) \ invalid = 1; \ while ((*cur >= '0') && (*cur <= '9')) { \ mult /= 10; \ num += (*cur - '0') * mult; \ cur++; \ } \ } /** * _xmlSchemaParseGMonth: * @dt: pointer to a date structure * @str: pointer to the string to analyze * * Parses a xs:gMonth without time zone and fills in the appropriate * field of the @dt structure. @str is updated to point just after the * xs:gMonth. * * Returns 0 or the error code */ static int _xmlSchemaParseGMonth (xmlSchemaValDatePtr dt, const xmlChar **str) { const xmlChar *cur = *str; int ret = 0; unsigned int value = 0; PARSE_2_DIGITS(value, cur, ret); if (ret != 0) return ret; if (!VALID_MONTH(value)) return 2; dt->mon = value; *str = cur; return 0; } /** * _xmlSchemaParseGDay: * @dt: pointer to a date structure * @str: pointer to the string to analyze * * Parses a xs:gDay without time zone and fills in the appropriate * field of the @dt structure. @str is updated to point just after the * xs:gDay. * * Returns 0 or the error code */ static int _xmlSchemaParseGDay (xmlSchemaValDatePtr dt, const xmlChar **str) { const xmlChar *cur = *str; int ret = 0; unsigned int value = 0; PARSE_2_DIGITS(value, cur, ret); if (ret != 0) return ret; if (!VALID_DAY(value)) return 2; dt->day = value; *str = cur; return 0; } /** * _xmlSchemaParseTime: * @dt: pointer to a date structure * @str: pointer to the string to analyze * * Parses a xs:time without time zone and fills in the appropriate * fields of the @dt structure. @str is updated to point just after the * xs:time. * In case of error, values of @dt fields are undefined. * * Returns 0 or the error code */ static int _xmlSchemaParseTime (xmlSchemaValDatePtr dt, const xmlChar **str) { const xmlChar *cur = *str; int ret = 0; int value = 0; PARSE_2_DIGITS(value, cur, ret); if (ret != 0) return ret; if (*cur != ':') return 1; if (!VALID_HOUR(value)) return 2; cur++; /* the ':' insures this string is xs:time */ dt->hour = value; PARSE_2_DIGITS(value, cur, ret); if (ret != 0) return ret; if (!VALID_MIN(value)) return 2; dt->min = value; if (*cur != ':') return 1; cur++; PARSE_FLOAT(dt->sec, cur, ret); if (ret != 0) return ret; if ((!VALID_SEC(dt->sec)) || (!VALID_TZO(dt->tzo))) return 2; *str = cur; return 0; } /** * _xmlSchemaParseTimeZone: * @dt: pointer to a date structure * @str: pointer to the string to analyze * * Parses a time zone without time zone and fills in the appropriate * field of the @dt structure. @str is updated to point just after the * time zone. * * Returns 0 or the error code */ static int _xmlSchemaParseTimeZone (xmlSchemaValDatePtr dt, const xmlChar **str) { const xmlChar *cur; int ret = 0; if (str == NULL) return -1; cur = *str; switch (*cur) { case 0: dt->tz_flag = 0; dt->tzo = 0; break; case 'Z': dt->tz_flag = 1; dt->tzo = 0; cur++; break; case '+': case '-': { int isneg = 0, tmp = 0; isneg = (*cur == '-'); cur++; PARSE_2_DIGITS(tmp, cur, ret); if (ret != 0) return ret; if (!VALID_HOUR(tmp)) return 2; if (*cur != ':') return 1; cur++; dt->tzo = tmp * 60; PARSE_2_DIGITS(tmp, cur, ret); if (ret != 0) return ret; if (!VALID_MIN(tmp)) return 2; dt->tzo += tmp; if (isneg) dt->tzo = - dt->tzo; if (!VALID_TZO(dt->tzo)) return 2; dt->tz_flag = 1; break; } default: return 1; } *str = cur; return 0; } /** * _xmlSchemaBase64Decode: * @ch: a character * * Converts a base64 encoded character to its base 64 value. * * Returns 0-63 (value), 64 (pad), or -1 (not recognized) */ static int _xmlSchemaBase64Decode (const xmlChar ch) { if (('A' <= ch) && (ch <= 'Z')) return ch - 'A'; if (('a' <= ch) && (ch <= 'z')) return ch - 'a' + 26; if (('0' <= ch) && (ch <= '9')) return ch - '0' + 52; if ('+' == ch) return 62; if ('/' == ch) return 63; if ('=' == ch) return 64; return -1; } /**************************************************************** * * * XML Schema Dates/Times Datatypes Handling * * * ****************************************************************/ /** * PARSE_DIGITS: * @num: the integer to fill in * @cur: an #xmlChar * * @num_type: an integer flag * * Parses a digits integer and updates @num with the value. @cur is * updated to point just after the integer. * In case of error, @num_type is set to -1, values of @num and * @cur are undefined. */ #define PARSE_DIGITS(num, cur, num_type) \ if ((*cur < '0') || (*cur > '9')) \ num_type = -1; \ else \ while ((*cur >= '0') && (*cur <= '9')) { \ num = num * 10 + (*cur - '0'); \ cur++; \ } /** * PARSE_NUM: * @num: the double to fill in * @cur: an #xmlChar * * @num_type: an integer flag * * Parses a float or integer and updates @num with the value. @cur is * updated to point just after the number. If the number is a float, * then it must have an integer part and a decimal part; @num_type will * be set to 1. If there is no decimal part, @num_type is set to zero. * In case of error, @num_type is set to -1, values of @num and * @cur are undefined. */ #define PARSE_NUM(num, cur, num_type) \ num = 0; \ PARSE_DIGITS(num, cur, num_type); \ if (!num_type && (*cur == '.')) { \ double mult = 1; \ cur++; \ if ((*cur < '0') || (*cur > '9')) \ num_type = -1; \ else \ num_type = 1; \ while ((*cur >= '0') && (*cur <= '9')) { \ mult /= 10; \ num += (*cur - '0') * mult; \ cur++; \ } \ } /** * xmlSchemaValidateDates: * @type: the expected type or XML_SCHEMAS_UNKNOWN * @dateTime: string to analyze * @val: the return computed value * * Check that @dateTime conforms to the lexical space of one of the date types. * if true a value is computed and returned in @val. * * Returns 0 if this validates, a positive error code number otherwise * and -1 in case of internal or API error. */ static int xmlSchemaValidateDates (xmlSchemaValType type, const xmlChar *dateTime, xmlSchemaValPtr *val, int collapse) { xmlSchemaValPtr dt; int ret; const xmlChar *cur = dateTime; #define RETURN_TYPE_IF_VALID(t) \ if (IS_TZO_CHAR(*cur)) { \ ret = _xmlSchemaParseTimeZone(&(dt->value.date), &cur); \ if (ret == 0) { \ if (*cur != 0) \ goto error; \ dt->type = t; \ goto done; \ } \ } if (dateTime == NULL) return -1; if (collapse) while IS_WSP_BLANK_CH(*cur) cur++; if ((*cur != '-') && (*cur < '0') && (*cur > '9')) return 1; dt = xmlSchemaNewValue(XML_SCHEMAS_UNKNOWN); if (dt == NULL) return -1; if ((cur[0] == '-') && (cur[1] == '-')) { /* * It's an incomplete date (xs:gMonthDay, xs:gMonth or * xs:gDay) */ cur += 2; /* is it an xs:gDay? */ if (*cur == '-') { if (type == XML_SCHEMAS_GMONTH) goto error; ++cur; ret = _xmlSchemaParseGDay(&(dt->value.date), &cur); if (ret != 0) goto error; RETURN_TYPE_IF_VALID(XML_SCHEMAS_GDAY); goto error; } /* * it should be an xs:gMonthDay or xs:gMonth */ ret = _xmlSchemaParseGMonth(&(dt->value.date), &cur); if (ret != 0) goto error; /* * a '-' char could indicate this type is xs:gMonthDay or * a negative time zone offset. Check for xs:gMonthDay first. * Also the first three char's of a negative tzo (-MM:SS) can * appear to be a valid day; so even if the day portion * of the xs:gMonthDay verifies, we must insure it was not * a tzo. */ if (*cur == '-') { const xmlChar *rewnd = cur; cur++; ret = _xmlSchemaParseGDay(&(dt->value.date), &cur); if ((ret == 0) && ((*cur == 0) || (*cur != ':'))) { /* * we can use the VALID_MDAY macro to validate the month * and day because the leap year test will flag year zero * as a leap year (even though zero is an invalid year). * FUTURE TODO: Zero will become valid in XML Schema 1.1 * probably. */ if (VALID_MDAY((&(dt->value.date)))) { RETURN_TYPE_IF_VALID(XML_SCHEMAS_GMONTHDAY); goto error; } } /* * not xs:gMonthDay so rewind and check if just xs:gMonth * with an optional time zone. */ cur = rewnd; } RETURN_TYPE_IF_VALID(XML_SCHEMAS_GMONTH); goto error; } /* * It's a right-truncated date or an xs:time. * Try to parse an xs:time then fallback on right-truncated dates. */ if ((*cur >= '0') && (*cur <= '9')) { ret = _xmlSchemaParseTime(&(dt->value.date), &cur); if (ret == 0) { /* it's an xs:time */ RETURN_TYPE_IF_VALID(XML_SCHEMAS_TIME); } } /* fallback on date parsing */ cur = dateTime; ret = _xmlSchemaParseGYear(&(dt->value.date), &cur); if (ret != 0) goto error; /* is it an xs:gYear? */ RETURN_TYPE_IF_VALID(XML_SCHEMAS_GYEAR); if (*cur != '-') goto error; cur++; ret = _xmlSchemaParseGMonth(&(dt->value.date), &cur); if (ret != 0) goto error; /* is it an xs:gYearMonth? */ RETURN_TYPE_IF_VALID(XML_SCHEMAS_GYEARMONTH); if (*cur != '-') goto error; cur++; ret = _xmlSchemaParseGDay(&(dt->value.date), &cur); if ((ret != 0) || !VALID_DATE((&(dt->value.date)))) goto error; /* is it an xs:date? */ RETURN_TYPE_IF_VALID(XML_SCHEMAS_DATE); if (*cur != 'T') goto error; cur++; /* it should be an xs:dateTime */ ret = _xmlSchemaParseTime(&(dt->value.date), &cur); if (ret != 0) goto error; ret = _xmlSchemaParseTimeZone(&(dt->value.date), &cur); if (collapse) while IS_WSP_BLANK_CH(*cur) cur++; if ((ret != 0) || (*cur != 0) || (!(VALID_DATETIME((&(dt->value.date)))))) goto error; dt->type = XML_SCHEMAS_DATETIME; done: #if 1 if ((type != XML_SCHEMAS_UNKNOWN) && (type != dt->type)) goto error; #else /* * insure the parsed type is equal to or less significant (right * truncated) than the desired type. */ if ((type != XML_SCHEMAS_UNKNOWN) && (type != dt->type)) { /* time only matches time */ if ((type == XML_SCHEMAS_TIME) && (dt->type == XML_SCHEMAS_TIME)) goto error; if ((type == XML_SCHEMAS_DATETIME) && ((dt->type != XML_SCHEMAS_DATE) || (dt->type != XML_SCHEMAS_GYEARMONTH) || (dt->type != XML_SCHEMAS_GYEAR))) goto error; if ((type == XML_SCHEMAS_DATE) && ((dt->type != XML_SCHEMAS_GYEAR) || (dt->type != XML_SCHEMAS_GYEARMONTH))) goto error; if ((type == XML_SCHEMAS_GYEARMONTH) && (dt->type != XML_SCHEMAS_GYEAR)) goto error; if ((type == XML_SCHEMAS_GMONTHDAY) && (dt->type != XML_SCHEMAS_GMONTH)) goto error; } #endif if (val != NULL) *val = dt; else xmlSchemaFreeValue(dt); return 0; error: if (dt != NULL) xmlSchemaFreeValue(dt); return 1; } /** * xmlSchemaValidateDuration: * @type: the predefined type * @duration: string to analyze * @val: the return computed value * * Check that @duration conforms to the lexical space of the duration type. * if true a value is computed and returned in @val. * * Returns 0 if this validates, a positive error code number otherwise * and -1 in case of internal or API error. */ static int xmlSchemaValidateDuration (xmlSchemaTypePtr type ATTRIBUTE_UNUSED, const xmlChar *duration, xmlSchemaValPtr *val, int collapse) { const xmlChar *cur = duration; xmlSchemaValPtr dur; int isneg = 0; unsigned int seq = 0; double num; int num_type = 0; /* -1 = invalid, 0 = int, 1 = floating */ const xmlChar desig[] = {'Y', 'M', 'D', 'H', 'M', 'S'}; const double multi[] = { 0.0, 0.0, 86400.0, 3600.0, 60.0, 1.0, 0.0}; if (duration == NULL) return -1; if (collapse) while IS_WSP_BLANK_CH(*cur) cur++; if (*cur == '-') { isneg = 1; cur++; } /* duration must start with 'P' (after sign) */ if (*cur++ != 'P') return 1; if (*cur == 0) return 1; dur = xmlSchemaNewValue(XML_SCHEMAS_DURATION); if (dur == NULL) return -1; while (*cur != 0) { /* input string should be empty or invalid date/time item */ if (seq >= sizeof(desig)) goto error; /* T designator must be present for time items */ if (*cur == 'T') { if (seq <= 3) { seq = 3; cur++; } else return 1; } else if (seq == 3) goto error; /* parse the number portion of the item */ PARSE_NUM(num, cur, num_type); if ((num_type == -1) || (*cur == 0)) goto error; /* update duration based on item type */ while (seq < sizeof(desig)) { if (*cur == desig[seq]) { /* verify numeric type; only seconds can be float */ if ((num_type != 0) && (seq < (sizeof(desig)-1))) goto error; switch (seq) { case 0: dur->value.dur.mon = (long)num * 12; break; case 1: dur->value.dur.mon += (long)num; break; default: /* convert to seconds using multiplier */ dur->value.dur.sec += num * multi[seq]; seq++; break; } break; /* exit loop */ } /* no date designators found? */ if ((++seq == 3) || (seq == 6)) goto error; } cur++; if (collapse) while IS_WSP_BLANK_CH(*cur) cur++; } if (isneg) { dur->value.dur.mon = -dur->value.dur.mon; dur->value.dur.day = -dur->value.dur.day; dur->value.dur.sec = -dur->value.dur.sec; } if (val != NULL) *val = dur; else xmlSchemaFreeValue(dur); return 0; error: if (dur != NULL) xmlSchemaFreeValue(dur); return 1; } /** * xmlSchemaStrip: * @value: a value * * Removes the leading and ending spaces of a string * * Returns the new string or NULL if no change was required. */ static xmlChar * xmlSchemaStrip(const xmlChar *value) { const xmlChar *start = value, *end, *f; if (value == NULL) return(NULL); while ((*start != 0) && (IS_BLANK_CH(*start))) start++; end = start; while (*end != 0) end++; f = end; end--; while ((end > start) && (IS_BLANK_CH(*end))) end--; end++; if ((start == value) && (f == end)) return(NULL); return(xmlStrndup(start, end - start)); } /** * xmlSchemaWhiteSpaceReplace: * @value: a value * * Replaces 0xd, 0x9 and 0xa with a space. * * Returns the new string or NULL if no change was required. */ xmlChar * xmlSchemaWhiteSpaceReplace(const xmlChar *value) { const xmlChar *cur = value; xmlChar *ret = NULL, *mcur; if (value == NULL) return(NULL); while ((*cur != 0) && (((*cur) != 0xd) && ((*cur) != 0x9) && ((*cur) != 0xa))) { cur++; } if (*cur == 0) return (NULL); ret = xmlStrdup(value); /* TODO FIXME: I guess gcc will bark at this. */ mcur = (xmlChar *) (ret + (cur - value)); do { if ( ((*mcur) == 0xd) || ((*mcur) == 0x9) || ((*mcur) == 0xa) ) *mcur = ' '; mcur++; } while (*mcur != 0); return(ret); } /** * xmlSchemaCollapseString: * @value: a value * * Removes and normalize white spaces in the string * * Returns the new string or NULL if no change was required. */ xmlChar * xmlSchemaCollapseString(const xmlChar *value) { const xmlChar *start = value, *end, *f; xmlChar *g; int col = 0; if (value == NULL) return(NULL); while ((*start != 0) && (IS_BLANK_CH(*start))) start++; end = start; while (*end != 0) { if ((*end == ' ') && (IS_BLANK_CH(end[1]))) { col = end - start; break; } else if ((*end == 0xa) || (*end == 0x9) || (*end == 0xd)) { col = end - start; break; } end++; } if (col == 0) { f = end; end--; while ((end > start) && (IS_BLANK_CH(*end))) end--; end++; if ((start == value) && (f == end)) return(NULL); return(xmlStrndup(start, end - start)); } start = xmlStrdup(start); if (start == NULL) return(NULL); g = (xmlChar *) (start + col); end = g; while (*end != 0) { if (IS_BLANK_CH(*end)) { end++; while (IS_BLANK_CH(*end)) end++; if (*end != 0) *g++ = ' '; } else *g++ = *end++; } *g = 0; return((xmlChar *) start); } /** * xmlSchemaValAtomicListNode: * @type: the predefined atomic type for a token in the list * @value: the list value to check * @ret: the return computed value * @node: the node containing the value * * Check that a value conforms to the lexical space of the predefined * list type. if true a value is computed and returned in @ret. * * Returns the number of items if this validates, a negative error code * number otherwise */ static int xmlSchemaValAtomicListNode(xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *ret, xmlNodePtr node) { xmlChar *val, *cur, *endval; int nb_values = 0; int tmp = 0; if (value == NULL) { return(-1); } val = xmlStrdup(value); if (val == NULL) { return(-1); } if (ret != NULL) { *ret = NULL; } cur = val; /* * Split the list */ while (IS_BLANK_CH(*cur)) *cur++ = 0; while (*cur != 0) { if (IS_BLANK_CH(*cur)) { *cur = 0; cur++; while (IS_BLANK_CH(*cur)) *cur++ = 0; } else { nb_values++; cur++; while ((*cur != 0) && (!IS_BLANK_CH(*cur))) cur++; } } if (nb_values == 0) { xmlFree(val); return(nb_values); } endval = cur; cur = val; while ((*cur == 0) && (cur != endval)) cur++; while (cur != endval) { tmp = xmlSchemaValPredefTypeNode(type, cur, NULL, node); if (tmp != 0) break; while (*cur != 0) cur++; while ((*cur == 0) && (cur != endval)) cur++; } /* TODO what return value ? c.f. bug #158628 if (ret != NULL) { TODO } */ xmlFree(val); if (tmp == 0) return(nb_values); return(-1); } /** * xmlSchemaParseUInt: * @str: pointer to the string R/W * @llo: pointer to the low result * @lmi: pointer to the mid result * @lhi: pointer to the high result * * Parse an unsigned long into 3 fields. * * Returns the number of significant digits in the number or * -1 if overflow of the capacity */ static int xmlSchemaParseUInt(const xmlChar **str, unsigned long *llo, unsigned long *lmi, unsigned long *lhi) { unsigned long lo = 0, mi = 0, hi = 0; const xmlChar *tmp, *cur = *str; int ret = 0, i = 0; while (*cur == '0') { /* ignore leading zeroes */ cur++; } tmp = cur; while ((*tmp != 0) && (*tmp >= '0') && (*tmp <= '9')) { i++;tmp++;ret++; } if (i > 24) { *str = tmp; return(-1); } while (i > 16) { hi = hi * 10 + (*cur++ - '0'); i--; } while (i > 8) { mi = mi * 10 + (*cur++ - '0'); i--; } while (i > 0) { lo = lo * 10 + (*cur++ - '0'); i--; } *str = cur; *llo = lo; *lmi = mi; *lhi = hi; return(ret); } /** * xmlSchemaValAtomicType: * @type: the predefined type * @value: the value to check * @val: the return computed value * @node: the node containing the value * flags: flags to control the vlidation * * Check that a value conforms to the lexical space of the atomic type. * if true a value is computed and returned in @val. * This checks the value space for list types as well (IDREFS, NMTOKENS). * * Returns 0 if this validates, a positive error code number otherwise * and -1 in case of internal or API error. */ static int xmlSchemaValAtomicType(xmlSchemaTypePtr type, const xmlChar * value, xmlSchemaValPtr * val, xmlNodePtr node, int flags, xmlSchemaWhitespaceValueType ws, int normOnTheFly, int applyNorm, int createStringValue) { xmlSchemaValPtr v; xmlChar *norm = NULL; int ret = 0; if (xmlSchemaTypesInitialized == 0) xmlSchemaInitTypes(); if (type == NULL) return (-1); /* * validating a non existant text node is similar to validating * an empty one. */ if (value == NULL) value = BAD_CAST ""; if (val != NULL) *val = NULL; if ((flags == 0) && (value != NULL)) { if ((type->builtInType != XML_SCHEMAS_STRING) && (type->builtInType != XML_SCHEMAS_ANYTYPE) && (type->builtInType != XML_SCHEMAS_ANYSIMPLETYPE)) { if (type->builtInType == XML_SCHEMAS_NORMSTRING) norm = xmlSchemaWhiteSpaceReplace(value); else norm = xmlSchemaCollapseString(value); if (norm != NULL) value = norm; } } switch (type->builtInType) { case XML_SCHEMAS_UNKNOWN: goto error; case XML_SCHEMAS_ANYTYPE: case XML_SCHEMAS_ANYSIMPLETYPE: if ((createStringValue) && (val != NULL)) { v = xmlSchemaNewValue(XML_SCHEMAS_ANYSIMPLETYPE); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } goto return0; case XML_SCHEMAS_STRING: if (! normOnTheFly) { const xmlChar *cur = value; if (ws == XML_SCHEMA_WHITESPACE_REPLACE) { while (*cur != 0) { if ((*cur == 0xd) || (*cur == 0xa) || (*cur == 0x9)) { goto return1; } else { cur++; } } } else if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) { while (*cur != 0) { if ((*cur == 0xd) || (*cur == 0xa) || (*cur == 0x9)) { goto return1; } else if IS_WSP_SPACE_CH(*cur) { cur++; if IS_WSP_SPACE_CH(*cur) goto return1; } else { cur++; } } } } if (createStringValue && (val != NULL)) { if (applyNorm) { if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) norm = xmlSchemaCollapseString(value); else if (ws == XML_SCHEMA_WHITESPACE_REPLACE) norm = xmlSchemaWhiteSpaceReplace(value); if (norm != NULL) value = norm; } v = xmlSchemaNewValue(XML_SCHEMAS_STRING); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } goto return0; case XML_SCHEMAS_NORMSTRING:{ if (normOnTheFly) { if (applyNorm) { if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) norm = xmlSchemaCollapseString(value); else norm = xmlSchemaWhiteSpaceReplace(value); if (norm != NULL) value = norm; } } else { const xmlChar *cur = value; while (*cur != 0) { if ((*cur == 0xd) || (*cur == 0xa) || (*cur == 0x9)) { goto return1; } else { cur++; } } } if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_NORMSTRING); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } goto return0; } case XML_SCHEMAS_DECIMAL:{ const xmlChar *cur = value; unsigned int len, neg, integ, hasLeadingZeroes; xmlChar cval[25]; xmlChar *cptr = cval; if ((cur == NULL) || (*cur == 0)) goto return1; /* * xs:decimal has a whitespace-facet value of 'collapse'. */ if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; /* * First we handle an optional sign. */ neg = 0; if (*cur == '-') { neg = 1; cur++; } else if (*cur == '+') cur++; /* * Disallow: "", "-", "- " */ if (*cur == 0) goto return1; /* * Next we "pre-parse" the number, in preparation for calling * the common routine xmlSchemaParseUInt. We get rid of any * leading zeroes (because we have reserved only 25 chars), * and note the position of a decimal point. */ len = 0; integ = ~0u; hasLeadingZeroes = 0; /* * Skip leading zeroes. */ while (*cur == '0') { cur++; hasLeadingZeroes = 1; } if (*cur != 0) { do { if ((*cur >= '0') && (*cur <= '9')) { *cptr++ = *cur++; len++; } else if (*cur == '.') { cur++; integ = len; do { if ((*cur >= '0') && (*cur <= '9')) { *cptr++ = *cur++; len++; } else break; } while (len < 24); /* * Disallow "." but allow "00." */ if ((len == 0) && (!hasLeadingZeroes)) goto return1; break; } else break; } while (len < 24); } if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; if (*cur != 0) goto return1; /* error if any extraneous chars */ if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_DECIMAL); if (v != NULL) { /* * Now evaluate the significant digits of the number */ if (len != 0) { if (integ != ~0u) { /* * Get rid of trailing zeroes in the * fractional part. */ while ((len != integ) && (*(cptr-1) == '0')) { cptr--; len--; } } /* * Terminate the (preparsed) string. */ if (len != 0) { *cptr = 0; cptr = cval; xmlSchemaParseUInt((const xmlChar **)&cptr, &v->value.decimal.lo, &v->value.decimal.mi, &v->value.decimal.hi); } } /* * Set the total digits to 1 if a zero value. */ v->value.decimal.sign = neg; if (len == 0) { /* Speedup for zero values. */ v->value.decimal.total = 1; } else { v->value.decimal.total = len; if (integ == ~0u) v->value.decimal.frac = 0; else v->value.decimal.frac = len - integ; } *val = v; } } goto return0; } case XML_SCHEMAS_TIME: case XML_SCHEMAS_GDAY: case XML_SCHEMAS_GMONTH: case XML_SCHEMAS_GMONTHDAY: case XML_SCHEMAS_GYEAR: case XML_SCHEMAS_GYEARMONTH: case XML_SCHEMAS_DATE: case XML_SCHEMAS_DATETIME: ret = xmlSchemaValidateDates(type->builtInType, value, val, normOnTheFly); break; case XML_SCHEMAS_DURATION: ret = xmlSchemaValidateDuration(type, value, val, normOnTheFly); break; case XML_SCHEMAS_FLOAT: case XML_SCHEMAS_DOUBLE:{ const xmlChar *cur = value; int neg = 0; if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; if ((cur[0] == 'N') && (cur[1] == 'a') && (cur[2] == 'N')) { cur += 3; if (*cur != 0) goto return1; if (val != NULL) { if (type == xmlSchemaTypeFloatDef) { v = xmlSchemaNewValue(XML_SCHEMAS_FLOAT); if (v != NULL) { v->value.f = (float) xmlXPathNAN; } else { xmlSchemaFreeValue(v); goto error; } } else { v = xmlSchemaNewValue(XML_SCHEMAS_DOUBLE); if (v != NULL) { v->value.d = xmlXPathNAN; } else { xmlSchemaFreeValue(v); goto error; } } *val = v; } goto return0; } if (*cur == '-') { neg = 1; cur++; } if ((cur[0] == 'I') && (cur[1] == 'N') && (cur[2] == 'F')) { cur += 3; if (*cur != 0) goto return1; if (val != NULL) { if (type == xmlSchemaTypeFloatDef) { v = xmlSchemaNewValue(XML_SCHEMAS_FLOAT); if (v != NULL) { if (neg) v->value.f = (float) xmlXPathNINF; else v->value.f = (float) xmlXPathPINF; } else { xmlSchemaFreeValue(v); goto error; } } else { v = xmlSchemaNewValue(XML_SCHEMAS_DOUBLE); if (v != NULL) { if (neg) v->value.d = xmlXPathNINF; else v->value.d = xmlXPathPINF; } else { xmlSchemaFreeValue(v); goto error; } } *val = v; } goto return0; } if ((neg == 0) && (*cur == '+')) cur++; if ((cur[0] == 0) || (cur[0] == '+') || (cur[0] == '-')) goto return1; while ((*cur >= '0') && (*cur <= '9')) { cur++; } if (*cur == '.') { cur++; while ((*cur >= '0') && (*cur <= '9')) cur++; } if ((*cur == 'e') || (*cur == 'E')) { cur++; if ((*cur == '-') || (*cur == '+')) cur++; while ((*cur >= '0') && (*cur <= '9')) cur++; } if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; if (*cur != 0) goto return1; if (val != NULL) { if (type == xmlSchemaTypeFloatDef) { v = xmlSchemaNewValue(XML_SCHEMAS_FLOAT); if (v != NULL) { /* * TODO: sscanf seems not to give the correct * value for extremely high/low values. * E.g. "1E-149" results in zero. */ if (sscanf((const char *) value, "%f", &(v->value.f)) == 1) { *val = v; } else { xmlSchemaFreeValue(v); goto return1; } } else { goto error; } } else { v = xmlSchemaNewValue(XML_SCHEMAS_DOUBLE); if (v != NULL) { /* * TODO: sscanf seems not to give the correct * value for extremely high/low values. */ if (sscanf((const char *) value, "%lf", &(v->value.d)) == 1) { *val = v; } else { xmlSchemaFreeValue(v); goto return1; } } else { goto error; } } } goto return0; } case XML_SCHEMAS_BOOLEAN:{ const xmlChar *cur = value; if (normOnTheFly) { while IS_WSP_BLANK_CH(*cur) cur++; if (*cur == '0') { ret = 0; cur++; } else if (*cur == '1') { ret = 1; cur++; } else if (*cur == 't') { cur++; if ((*cur++ == 'r') && (*cur++ == 'u') && (*cur++ == 'e')) { ret = 1; } else goto return1; } else if (*cur == 'f') { cur++; if ((*cur++ == 'a') && (*cur++ == 'l') && (*cur++ == 's') && (*cur++ == 'e')) { ret = 0; } else goto return1; } else goto return1; if (*cur != 0) { while IS_WSP_BLANK_CH(*cur) cur++; if (*cur != 0) goto return1; } } else { if ((cur[0] == '0') && (cur[1] == 0)) ret = 0; else if ((cur[0] == '1') && (cur[1] == 0)) ret = 1; else if ((cur[0] == 't') && (cur[1] == 'r') && (cur[2] == 'u') && (cur[3] == 'e') && (cur[4] == 0)) ret = 1; else if ((cur[0] == 'f') && (cur[1] == 'a') && (cur[2] == 'l') && (cur[3] == 's') && (cur[4] == 'e') && (cur[5] == 0)) ret = 0; else goto return1; } if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_BOOLEAN); if (v != NULL) { v->value.b = ret; *val = v; } else { goto error; } } goto return0; } case XML_SCHEMAS_TOKEN:{ const xmlChar *cur = value; if (! normOnTheFly) { while (*cur != 0) { if ((*cur == 0xd) || (*cur == 0xa) || (*cur == 0x9)) { goto return1; } else if (*cur == ' ') { cur++; if (*cur == 0) goto return1; if (*cur == ' ') goto return1; } else { cur++; } } } if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_TOKEN); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } goto return0; } case XML_SCHEMAS_LANGUAGE: if (normOnTheFly) { norm = xmlSchemaCollapseString(value); if (norm != NULL) value = norm; } if (xmlCheckLanguageID(value) == 1) { if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_LANGUAGE); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } goto return0; } goto return1; case XML_SCHEMAS_NMTOKEN: if (xmlValidateNMToken(value, 1) == 0) { if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_NMTOKEN); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } goto return0; } goto return1; case XML_SCHEMAS_NMTOKENS: ret = xmlSchemaValAtomicListNode(xmlSchemaTypeNmtokenDef, value, val, node); if (ret > 0) ret = 0; else ret = 1; goto done; case XML_SCHEMAS_NAME: ret = xmlValidateName(value, 1); if ((ret == 0) && (val != NULL) && (value != NULL)) { v = xmlSchemaNewValue(XML_SCHEMAS_NAME); if (v != NULL) { const xmlChar *start = value, *end; while (IS_BLANK_CH(*start)) start++; end = start; while ((*end != 0) && (!IS_BLANK_CH(*end))) end++; v->value.str = xmlStrndup(start, end - start); *val = v; } else { goto error; } } goto done; case XML_SCHEMAS_QNAME:{ const xmlChar *uri = NULL; xmlChar *local = NULL; ret = xmlValidateQName(value, 1); if (ret != 0) goto done; if (node != NULL) { xmlChar *prefix; xmlNsPtr ns; local = xmlSplitQName2(value, &prefix); ns = xmlSearchNs(node->doc, node, prefix); if ((ns == NULL) && (prefix != NULL)) { xmlFree(prefix); if (local != NULL) xmlFree(local); goto return1; } if (ns != NULL) uri = ns->href; if (prefix != NULL) xmlFree(prefix); } if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_QNAME); if (v == NULL) { if (local != NULL) xmlFree(local); goto error; } if (local != NULL) v->value.qname.name = local; else v->value.qname.name = xmlStrdup(value); if (uri != NULL) v->value.qname.uri = xmlStrdup(uri); *val = v; } else if (local != NULL) xmlFree(local); goto done; } case XML_SCHEMAS_NCNAME: ret = xmlValidateNCName(value, 1); if ((ret == 0) && (val != NULL)) { v = xmlSchemaNewValue(XML_SCHEMAS_NCNAME); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } goto done; case XML_SCHEMAS_ID: ret = xmlValidateNCName(value, 1); if ((ret == 0) && (val != NULL)) { v = xmlSchemaNewValue(XML_SCHEMAS_ID); if (v != NULL) { v->value.str = xmlStrdup(value); *val = v; } else { goto error; } } if ((ret == 0) && (node != NULL) && (node->type == XML_ATTRIBUTE_NODE)) { xmlAttrPtr attr = (xmlAttrPtr) node; /* * NOTE: the IDness might have already be declared in the DTD */ if (attr->atype != XML_ATTRIBUTE_ID) { xmlIDPtr res; xmlChar *strip; strip = xmlSchemaStrip(value); if (strip != NULL) { res = xmlAddID(NULL, node->doc, strip, attr); xmlFree(strip); } else res = xmlAddID(NULL, node->doc, value, attr); if (res == NULL) { ret = 2; } else { attr->atype = XML_ATTRIBUTE_ID; } } } goto done; case XML_SCHEMAS_IDREF: ret = xmlValidateNCName(value, 1); if ((ret == 0) && (val != NULL)) { v = xmlSchemaNewValue(XML_SCHEMAS_IDREF); if (v == NULL) goto error; v->value.str = xmlStrdup(value); *val = v; } if ((ret == 0) && (node != NULL) && (node->type == XML_ATTRIBUTE_NODE)) { xmlAttrPtr attr = (xmlAttrPtr) node; xmlChar *strip; strip = xmlSchemaStrip(value); if (strip != NULL) { xmlAddRef(NULL, node->doc, strip, attr); xmlFree(strip); } else xmlAddRef(NULL, node->doc, value, attr); attr->atype = XML_ATTRIBUTE_IDREF; } goto done; case XML_SCHEMAS_IDREFS: ret = xmlSchemaValAtomicListNode(xmlSchemaTypeIdrefDef, value, val, node); if (ret < 0) ret = 2; else ret = 0; if ((ret == 0) && (node != NULL) && (node->type == XML_ATTRIBUTE_NODE)) { xmlAttrPtr attr = (xmlAttrPtr) node; attr->atype = XML_ATTRIBUTE_IDREFS; } goto done; case XML_SCHEMAS_ENTITY:{ xmlChar *strip; ret = xmlValidateNCName(value, 1); if ((node == NULL) || (node->doc == NULL)) ret = 3; if (ret == 0) { xmlEntityPtr ent; strip = xmlSchemaStrip(value); if (strip != NULL) { ent = xmlGetDocEntity(node->doc, strip); xmlFree(strip); } else { ent = xmlGetDocEntity(node->doc, value); } if ((ent == NULL) || (ent->etype != XML_EXTERNAL_GENERAL_UNPARSED_ENTITY)) ret = 4; } if ((ret == 0) && (val != NULL)) { TODO; } if ((ret == 0) && (node != NULL) && (node->type == XML_ATTRIBUTE_NODE)) { xmlAttrPtr attr = (xmlAttrPtr) node; attr->atype = XML_ATTRIBUTE_ENTITY; } goto done; } case XML_SCHEMAS_ENTITIES: if ((node == NULL) || (node->doc == NULL)) goto return3; ret = xmlSchemaValAtomicListNode(xmlSchemaTypeEntityDef, value, val, node); if (ret <= 0) ret = 1; else ret = 0; if ((ret == 0) && (node != NULL) && (node->type == XML_ATTRIBUTE_NODE)) { xmlAttrPtr attr = (xmlAttrPtr) node; attr->atype = XML_ATTRIBUTE_ENTITIES; } goto done; case XML_SCHEMAS_NOTATION:{ xmlChar *uri = NULL; xmlChar *local = NULL; ret = xmlValidateQName(value, 1); if ((ret == 0) && (node != NULL)) { xmlChar *prefix; local = xmlSplitQName2(value, &prefix); if (prefix != NULL) { xmlNsPtr ns; ns = xmlSearchNs(node->doc, node, prefix); if (ns == NULL) ret = 1; else if (val != NULL) uri = xmlStrdup(ns->href); } if ((local != NULL) && ((val == NULL) || (ret != 0))) xmlFree(local); if (prefix != NULL) xmlFree(prefix); } if ((node == NULL) || (node->doc == NULL)) ret = 3; if (ret == 0) { ret = xmlValidateNotationUse(NULL, node->doc, value); if (ret == 1) ret = 0; else ret = 1; } if ((ret == 0) && (val != NULL)) { v = xmlSchemaNewValue(XML_SCHEMAS_NOTATION); if (v != NULL) { if (local != NULL) v->value.qname.name = local; else v->value.qname.name = xmlStrdup(value); if (uri != NULL) v->value.qname.uri = uri; *val = v; } else { if (local != NULL) xmlFree(local); if (uri != NULL) xmlFree(uri); goto error; } } goto done; } case XML_SCHEMAS_ANYURI:{ if (*value != 0) { xmlURIPtr uri; if (normOnTheFly) { norm = xmlSchemaCollapseString(value); if (norm != NULL) value = norm; } uri = xmlParseURI((const char *) value); if (uri == NULL) goto return1; xmlFreeURI(uri); } if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_ANYURI); if (v == NULL) goto error; v->value.str = xmlStrdup(value); *val = v; } goto return0; } case XML_SCHEMAS_HEXBINARY:{ const xmlChar *cur = value, *start; xmlChar *base; int total, i = 0; if (cur == NULL) goto return1; if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; start = cur; while (((*cur >= '0') && (*cur <= '9')) || ((*cur >= 'A') && (*cur <= 'F')) || ((*cur >= 'a') && (*cur <= 'f'))) { i++; cur++; } if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; if (*cur != 0) goto return1; if ((i % 2) != 0) goto return1; if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_HEXBINARY); if (v == NULL) goto error; /* * Copy only the normalized piece. * CRITICAL TODO: Check this. */ cur = xmlStrndup(start, i); if (cur == NULL) { xmlSchemaTypeErrMemory(node, "allocating hexbin data"); xmlFree(v); goto return1; } total = i / 2; /* number of octets */ base = (xmlChar *) cur; while (i-- > 0) { if (*base >= 'a') *base = *base - ('a' - 'A'); base++; } v->value.hex.str = (xmlChar *) cur; v->value.hex.total = total; *val = v; } goto return0; } case XML_SCHEMAS_BASE64BINARY:{ /* ISSUE: * * Ignore all stray characters? (yes, currently) * Worry about long lines? (no, currently) * * rfc2045.txt: * * "The encoded output stream must be represented in lines of * no more than 76 characters each. All line breaks or other * characters not found in Table 1 must be ignored by decoding * software. In base64 data, characters other than those in * Table 1, line breaks, and other white space probably * indicate a transmission error, about which a warning * message or even a message rejection might be appropriate * under some circumstances." */ const xmlChar *cur = value; xmlChar *base; int total, i = 0, pad = 0; if (cur == NULL) goto return1; for (; *cur; ++cur) { int decc; decc = _xmlSchemaBase64Decode(*cur); if (decc < 0) ; else if (decc < 64) i++; else break; } for (; *cur; ++cur) { int decc; decc = _xmlSchemaBase64Decode(*cur); if (decc < 0) ; else if (decc < 64) goto return1; if (decc == 64) pad++; } /* rfc2045.txt: "Special processing is performed if fewer than * 24 bits are available at the end of the data being encoded. * A full encoding quantum is always completed at the end of a * body. When fewer than 24 input bits are available in an * input group, zero bits are added (on the right) to form an * integral number of 6-bit groups. Padding at the end of the * data is performed using the "=" character. Since all * base64 input is an integral number of octets, only the * following cases can arise: (1) the final quantum of * encoding input is an integral multiple of 24 bits; here, * the final unit of encoded output will be an integral * multiple ofindent: Standard input:701: Warning:old style * assignment ambiguity in "=*". Assuming "= *" 4 characters * with no "=" padding, (2) the final * quantum of encoding input is exactly 8 bits; here, the * final unit of encoded output will be two characters * followed by two "=" padding characters, or (3) the final * quantum of encoding input is exactly 16 bits; here, the * final unit of encoded output will be three characters * followed by one "=" padding character." */ total = 3 * (i / 4); if (pad == 0) { if (i % 4 != 0) goto return1; } else if (pad == 1) { int decc; if (i % 4 != 3) goto return1; for (decc = _xmlSchemaBase64Decode(*cur); (decc < 0) || (decc > 63); decc = _xmlSchemaBase64Decode(*cur)) --cur; /* 16bits in 24bits means 2 pad bits: nnnnnn nnmmmm mmmm00*/ /* 00111100 -> 0x3c */ if (decc & ~0x3c) goto return1; total += 2; } else if (pad == 2) { int decc; if (i % 4 != 2) goto return1; for (decc = _xmlSchemaBase64Decode(*cur); (decc < 0) || (decc > 63); decc = _xmlSchemaBase64Decode(*cur)) --cur; /* 8bits in 12bits means 4 pad bits: nnnnnn nn0000 */ /* 00110000 -> 0x30 */ if (decc & ~0x30) goto return1; total += 1; } else goto return1; if (val != NULL) { v = xmlSchemaNewValue(XML_SCHEMAS_BASE64BINARY); if (v == NULL) goto error; base = (xmlChar *) xmlMallocAtomic((i + pad + 1) * sizeof(xmlChar)); if (base == NULL) { xmlSchemaTypeErrMemory(node, "allocating base64 data"); xmlFree(v); goto return1; } v->value.base64.str = base; for (cur = value; *cur; ++cur) if (_xmlSchemaBase64Decode(*cur) >= 0) { *base = *cur; ++base; } *base = 0; v->value.base64.total = total; *val = v; } goto return0; } case XML_SCHEMAS_INTEGER: case XML_SCHEMAS_PINTEGER: case XML_SCHEMAS_NPINTEGER: case XML_SCHEMAS_NINTEGER: case XML_SCHEMAS_NNINTEGER:{ const xmlChar *cur = value; unsigned long lo, mi, hi; int sign = 0; if (cur == NULL) goto return1; if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; if (*cur == '-') { sign = 1; cur++; } else if (*cur == '+') cur++; ret = xmlSchemaParseUInt(&cur, &lo, &mi, &hi); if (ret == -1) goto return1; if (normOnTheFly) while IS_WSP_BLANK_CH(*cur) cur++; if (*cur != 0) goto return1; if (type->builtInType == XML_SCHEMAS_NPINTEGER) { if ((sign == 0) && ((hi != 0) || (mi != 0) || (lo != 0))) goto return1; } else if (type->builtInType == XML_SCHEMAS_PINTEGER) { if (sign == 1) goto return1; if ((hi == 0) && (mi == 0) && (lo == 0)) goto return1; } else if (type->builtInType == XML_SCHEMAS_NINTEGER) { if (sign == 0) goto return1; if ((hi == 0) && (mi == 0) && (lo == 0)) goto return1; } else if (type->builtInType == XML_SCHEMAS_NNINTEGER) { if ((sign == 1) && ((hi != 0) || (mi != 0) || (lo != 0))) goto return1; } if (val != NULL) { v = xmlSchemaNewValue(type->builtInType); if (v != NULL) { if (ret == 0) ret++; v->value.decimal.lo = lo; v->value.decimal.mi = mi; v->value.decimal.hi = hi; v->value.decimal.sign = sign; v->value.decimal.frac = 0; v->value.decimal.total = ret; *val = v; } } goto return0; } case XML_SCHEMAS_LONG: case XML_SCHEMAS_BYTE: case XML_SCHEMAS_SHORT: case XML_SCHEMAS_INT:{ const xmlChar *cur = value; unsigned long lo, mi, hi; int sign = 0; if (cur == NULL) goto return1; if (*cur == '-') { sign = 1; cur++; } else if (*cur == '+') cur++; ret = xmlSchemaParseUInt(&cur, &lo, &mi, &hi); if (ret < 0) goto return1; if (*cur != 0) goto return1; if (type->builtInType == XML_SCHEMAS_LONG) { if (hi >= 922) { if (hi > 922) goto return1; if (mi >= 33720368) { if (mi > 33720368) goto return1; if ((sign == 0) && (lo > 54775807)) goto return1; if ((sign == 1) && (lo > 54775808)) goto return1; } } } else if (type->builtInType == XML_SCHEMAS_INT) { if (hi != 0) goto return1; if (mi >= 21) { if (mi > 21) goto return1; if ((sign == 0) && (lo > 47483647)) goto return1; if ((sign == 1) && (lo > 47483648)) goto return1; } } else if (type->builtInType == XML_SCHEMAS_SHORT) { if ((mi != 0) || (hi != 0)) goto return1; if ((sign == 1) && (lo > 32768)) goto return1; if ((sign == 0) && (lo > 32767)) goto return1; } else if (type->builtInType == XML_SCHEMAS_BYTE) { if ((mi != 0) || (hi != 0)) goto return1; if ((sign == 1) && (lo > 128)) goto return1; if ((sign == 0) && (lo > 127)) goto return1; } if (val != NULL) { v = xmlSchemaNewValue(type->builtInType); if (v != NULL) { v->value.decimal.lo = lo; v->value.decimal.mi = mi; v->value.decimal.hi = hi; v->value.decimal.sign = sign; v->value.decimal.frac = 0; v->value.decimal.total = ret; *val = v; } } goto return0; } case XML_SCHEMAS_UINT: case XML_SCHEMAS_ULONG: case XML_SCHEMAS_USHORT: case XML_SCHEMAS_UBYTE:{ const xmlChar *cur = value; unsigned long lo, mi, hi; if (cur == NULL) goto return1; ret = xmlSchemaParseUInt(&cur, &lo, &mi, &hi); if (ret < 0) goto return1; if (*cur != 0) goto return1; if (type->builtInType == XML_SCHEMAS_ULONG) { if (hi >= 1844) { if (hi > 1844) goto return1; if (mi >= 67440737) { if (mi > 67440737) goto return1; if (lo > 9551615) goto return1; } } } else if (type->builtInType == XML_SCHEMAS_UINT) { if (hi != 0) goto return1; if (mi >= 42) { if (mi > 42) goto return1; if (lo > 94967295) goto return1; } } else if (type->builtInType == XML_SCHEMAS_USHORT) { if ((mi != 0) || (hi != 0)) goto return1; if (lo > 65535) goto return1; } else if (type->builtInType == XML_SCHEMAS_UBYTE) { if ((mi != 0) || (hi != 0)) goto return1; if (lo > 255) goto return1; } if (val != NULL) { v = xmlSchemaNewValue(type->builtInType); if (v != NULL) { v->value.decimal.lo = lo; v->value.decimal.mi = mi; v->value.decimal.hi = hi; v->value.decimal.sign = 0; v->value.decimal.frac = 0; v->value.decimal.total = ret; *val = v; } } goto return0; } } done: if (norm != NULL) xmlFree(norm); return (ret); return3: if (norm != NULL) xmlFree(norm); return (3); return1: if (norm != NULL) xmlFree(norm); return (1); return0: if (norm != NULL) xmlFree(norm); return (0); error: if (norm != NULL) xmlFree(norm); return (-1); } /** * xmlSchemaValPredefTypeNode: * @type: the predefined type * @value: the value to check * @val: the return computed value * @node: the node containing the value * * Check that a value conforms to the lexical space of the predefined type. * if true a value is computed and returned in @val. * * Returns 0 if this validates, a positive error code number otherwise * and -1 in case of internal or API error. */ int xmlSchemaValPredefTypeNode(xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val, xmlNodePtr node) { return(xmlSchemaValAtomicType(type, value, val, node, 0, XML_SCHEMA_WHITESPACE_UNKNOWN, 1, 1, 0)); } /** * xmlSchemaValPredefTypeNodeNoNorm: * @type: the predefined type * @value: the value to check * @val: the return computed value * @node: the node containing the value * * Check that a value conforms to the lexical space of the predefined type. * if true a value is computed and returned in @val. * This one does apply any normalization to the value. * * Returns 0 if this validates, a positive error code number otherwise * and -1 in case of internal or API error. */ int xmlSchemaValPredefTypeNodeNoNorm(xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val, xmlNodePtr node) { return(xmlSchemaValAtomicType(type, value, val, node, 1, XML_SCHEMA_WHITESPACE_UNKNOWN, 1, 0, 1)); } /** * xmlSchemaValidatePredefinedType: * @type: the predefined type * @value: the value to check * @val: the return computed value * * Check that a value conforms to the lexical space of the predefined type. * if true a value is computed and returned in @val. * * Returns 0 if this validates, a positive error code number otherwise * and -1 in case of internal or API error. */ int xmlSchemaValidatePredefinedType(xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val) { return(xmlSchemaValPredefTypeNode(type, value, val, NULL)); } /** * xmlSchemaCompareDecimals: * @x: a first decimal value * @y: a second decimal value * * Compare 2 decimals * * Returns -1 if x < y, 0 if x == y, 1 if x > y and -2 in case of error */ static int xmlSchemaCompareDecimals(xmlSchemaValPtr x, xmlSchemaValPtr y) { xmlSchemaValPtr swp; int order = 1, integx, integy, dlen; unsigned long hi, mi, lo; /* * First test: If x is -ve and not zero */ if ((x->value.decimal.sign) && ((x->value.decimal.lo != 0) || (x->value.decimal.mi != 0) || (x->value.decimal.hi != 0))) { /* * Then if y is -ve and not zero reverse the compare */ if ((y->value.decimal.sign) && ((y->value.decimal.lo != 0) || (y->value.decimal.mi != 0) || (y->value.decimal.hi != 0))) order = -1; /* * Otherwise (y >= 0) we have the answer */ else return (-1); /* * If x is not -ve and y is -ve we have the answer */ } else if ((y->value.decimal.sign) && ((y->value.decimal.lo != 0) || (y->value.decimal.mi != 0) || (y->value.decimal.hi != 0))) { return (1); } /* * If it's not simply determined by a difference in sign, * then we need to compare the actual values of the two nums. * To do this, we start by looking at the integral parts. * If the number of integral digits differ, then we have our * answer. */ integx = x->value.decimal.total - x->value.decimal.frac; integy = y->value.decimal.total - y->value.decimal.frac; /* * NOTE: We changed the "total" for values like "0.1" * (or "-0.1" or ".1") to be 1, which was 2 previously. * Therefore the special case, when such values are * compared with 0, needs to be handled separately; * otherwise a zero would be recognized incorrectly as * greater than those values. This has the nice side effect * that we gain an overall optimized comparison with zeroes. * Note that a "0" has a "total" of 1 already. */ if (integx == 1) { if (x->value.decimal.lo == 0) { if (integy != 1) return -order; else if (y->value.decimal.lo != 0) return -order; else return(0); } } if (integy == 1) { if (y->value.decimal.lo == 0) { if (integx != 1) return order; else if (x->value.decimal.lo != 0) return order; else return(0); } } if (integx > integy) return order; else if (integy > integx) return -order; /* * If the number of integral digits is the same for both numbers, * then things get a little more complicated. We need to "normalize" * the numbers in order to properly compare them. To do this, we * look at the total length of each number (length => number of * significant digits), and divide the "shorter" by 10 (decreasing * the length) until they are of equal length. */ dlen = x->value.decimal.total - y->value.decimal.total; if (dlen < 0) { /* y has more digits than x */ swp = x; hi = y->value.decimal.hi; mi = y->value.decimal.mi; lo = y->value.decimal.lo; dlen = -dlen; order = -order; } else { /* x has more digits than y */ swp = y; hi = x->value.decimal.hi; mi = x->value.decimal.mi; lo = x->value.decimal.lo; } while (dlen > 8) { /* in effect, right shift by 10**8 */ lo = mi; mi = hi; hi = 0; dlen -= 8; } while (dlen > 0) { unsigned long rem1, rem2; rem1 = (hi % 10) * 100000000L; hi = hi / 10; rem2 = (mi % 10) * 100000000L; mi = (mi + rem1) / 10; lo = (lo + rem2) / 10; dlen--; } if (hi > swp->value.decimal.hi) { return order; } else if (hi == swp->value.decimal.hi) { if (mi > swp->value.decimal.mi) { return order; } else if (mi == swp->value.decimal.mi) { if (lo > swp->value.decimal.lo) { return order; } else if (lo == swp->value.decimal.lo) { if (x->value.decimal.total == y->value.decimal.total) { return 0; } else { return order; } } } } return -order; } /** * xmlSchemaCompareDurations: * @x: a first duration value * @y: a second duration value * * Compare 2 durations * * Returns -1 if x < y, 0 if x == y, 1 if x > y, 2 if x <> y, and -2 in * case of error */ static int xmlSchemaCompareDurations(xmlSchemaValPtr x, xmlSchemaValPtr y) { long carry, mon, day; double sec; int invert = 1; long xmon, xday, myear, minday, maxday; static const long dayRange [2][12] = { { 0, 28, 59, 89, 120, 150, 181, 212, 242, 273, 303, 334, }, { 0, 31, 62, 92, 123, 153, 184, 215, 245, 276, 306, 337} }; if ((x == NULL) || (y == NULL)) return -2; /* months */ mon = x->value.dur.mon - y->value.dur.mon; /* seconds */ sec = x->value.dur.sec - y->value.dur.sec; carry = (long)sec / SECS_PER_DAY; sec -= (double)(carry * SECS_PER_DAY); /* days */ day = x->value.dur.day - y->value.dur.day + carry; /* easy test */ if (mon == 0) { if (day == 0) if (sec == 0.0) return 0; else if (sec < 0.0) return -1; else return 1; else if (day < 0) return -1; else return 1; } if (mon > 0) { if ((day >= 0) && (sec >= 0.0)) return 1; else { xmon = mon; xday = -day; } } else if ((day <= 0) && (sec <= 0.0)) { return -1; } else { invert = -1; xmon = -mon; xday = day; } myear = xmon / 12; if (myear == 0) { minday = 0; maxday = 0; } else { maxday = 366 * ((myear + 3) / 4) + 365 * ((myear - 1) % 4); minday = maxday - 1; } xmon = xmon % 12; minday += dayRange[0][xmon]; maxday += dayRange[1][xmon]; if ((maxday == minday) && (maxday == xday)) return(0); /* can this really happen ? */ if (maxday < xday) return(-invert); if (minday > xday) return(invert); /* indeterminate */ return 2; } /* * macros for adding date/times and durations */ #define FQUOTIENT(a,b) (floor(((double)a/(double)b))) #define MODULO(a,b) (a - FQUOTIENT(a,b) * b) #define FQUOTIENT_RANGE(a,low,high) (FQUOTIENT((a-low),(high-low))) #define MODULO_RANGE(a,low,high) ((MODULO((a-low),(high-low)))+low) /** * xmlSchemaDupVal: * @v: the #xmlSchemaValPtr value to duplicate * * Makes a copy of @v. The calling program is responsible for freeing * the returned value. * * returns a pointer to a duplicated #xmlSchemaValPtr or NULL if error. */ static xmlSchemaValPtr xmlSchemaDupVal (xmlSchemaValPtr v) { xmlSchemaValPtr ret = xmlSchemaNewValue(v->type); if (ret == NULL) return NULL; memcpy(ret, v, sizeof(xmlSchemaVal)); ret->next = NULL; return ret; } /** * xmlSchemaCopyValue: * @val: the precomputed value to be copied * * Copies the precomputed value. This duplicates any string within. * * Returns the copy or NULL if a copy for a data-type is not implemented. */ xmlSchemaValPtr xmlSchemaCopyValue(xmlSchemaValPtr val) { xmlSchemaValPtr ret = NULL, prev = NULL, cur; /* * Copy the string values. */ while (val != NULL) { switch (val->type) { case XML_SCHEMAS_ANYTYPE: case XML_SCHEMAS_IDREFS: case XML_SCHEMAS_ENTITIES: case XML_SCHEMAS_NMTOKENS: xmlSchemaFreeValue(ret); return (NULL); case XML_SCHEMAS_ANYSIMPLETYPE: case XML_SCHEMAS_STRING: case XML_SCHEMAS_NORMSTRING: case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: case XML_SCHEMAS_NAME: case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_ID: case XML_SCHEMAS_IDREF: case XML_SCHEMAS_ENTITY: case XML_SCHEMAS_NMTOKEN: case XML_SCHEMAS_ANYURI: cur = xmlSchemaDupVal(val); if (val->value.str != NULL) cur->value.str = xmlStrdup(BAD_CAST val->value.str); break; case XML_SCHEMAS_QNAME: case XML_SCHEMAS_NOTATION: cur = xmlSchemaDupVal(val); if (val->value.qname.name != NULL) cur->value.qname.name = xmlStrdup(BAD_CAST val->value.qname.name); if (val->value.qname.uri != NULL) cur->value.qname.uri = xmlStrdup(BAD_CAST val->value.qname.uri); break; case XML_SCHEMAS_HEXBINARY: cur = xmlSchemaDupVal(val); if (val->value.hex.str != NULL) cur->value.hex.str = xmlStrdup(BAD_CAST val->value.hex.str); break; case XML_SCHEMAS_BASE64BINARY: cur = xmlSchemaDupVal(val); if (val->value.base64.str != NULL) cur->value.base64.str = xmlStrdup(BAD_CAST val->value.base64.str); break; default: cur = xmlSchemaDupVal(val); break; } if (ret == NULL) ret = cur; else prev->next = cur; prev = cur; val = val->next; } return (ret); } /** * _xmlSchemaDateAdd: * @dt: an #xmlSchemaValPtr * @dur: an #xmlSchemaValPtr of type #XS_DURATION * * Compute a new date/time from @dt and @dur. This function assumes @dt * is either #XML_SCHEMAS_DATETIME, #XML_SCHEMAS_DATE, #XML_SCHEMAS_GYEARMONTH, * or #XML_SCHEMAS_GYEAR. The returned #xmlSchemaVal is the same type as * @dt. The calling program is responsible for freeing the returned value. * * Returns a pointer to a new #xmlSchemaVal or NULL if error. */ static xmlSchemaValPtr _xmlSchemaDateAdd (xmlSchemaValPtr dt, xmlSchemaValPtr dur) { xmlSchemaValPtr ret, tmp; long carry, tempdays, temp; xmlSchemaValDatePtr r, d; xmlSchemaValDurationPtr u; if ((dt == NULL) || (dur == NULL)) return NULL; ret = xmlSchemaNewValue(dt->type); if (ret == NULL) return NULL; /* make a copy so we don't alter the original value */ tmp = xmlSchemaDupVal(dt); if (tmp == NULL) { xmlSchemaFreeValue(ret); return NULL; } r = &(ret->value.date); d = &(tmp->value.date); u = &(dur->value.dur); /* normalization */ if (d->mon == 0) d->mon = 1; /* normalize for time zone offset */ u->sec -= (d->tzo * 60); d->tzo = 0; /* normalization */ if (d->day == 0) d->day = 1; /* month */ carry = d->mon + u->mon; r->mon = (unsigned int) MODULO_RANGE(carry, 1, 13); carry = (long) FQUOTIENT_RANGE(carry, 1, 13); /* year (may be modified later) */ r->year = d->year + carry; if (r->year == 0) { if (d->year > 0) r->year--; else r->year++; } /* time zone */ r->tzo = d->tzo; r->tz_flag = d->tz_flag; /* seconds */ r->sec = d->sec + u->sec; carry = (long) FQUOTIENT((long)r->sec, 60); if (r->sec != 0.0) { r->sec = MODULO(r->sec, 60.0); } /* minute */ carry += d->min; r->min = (unsigned int) MODULO(carry, 60); carry = (long) FQUOTIENT(carry, 60); /* hours */ carry += d->hour; r->hour = (unsigned int) MODULO(carry, 24); carry = (long)FQUOTIENT(carry, 24); /* * days * Note we use tempdays because the temporary values may need more * than 5 bits */ if ((VALID_YEAR(r->year)) && (VALID_MONTH(r->mon)) && (d->day > MAX_DAYINMONTH(r->year, r->mon))) tempdays = MAX_DAYINMONTH(r->year, r->mon); else if (d->day < 1) tempdays = 1; else tempdays = d->day; tempdays += u->day + carry; while (1) { if (tempdays < 1) { long tmon = (long) MODULO_RANGE((int)r->mon-1, 1, 13); long tyr = r->year + (long)FQUOTIENT_RANGE((int)r->mon-1, 1, 13); if (tyr == 0) tyr--; /* * Coverity detected an overrun in daysInMonth * of size 12 at position 12 with index variable "((r)->mon - 1)" */ if (tmon < 0) tmon = 0; if (tmon > 12) tmon = 12; tempdays += MAX_DAYINMONTH(tyr, tmon); carry = -1; } else if (tempdays > (long) MAX_DAYINMONTH(r->year, r->mon)) { tempdays = tempdays - MAX_DAYINMONTH(r->year, r->mon); carry = 1; } else break; temp = r->mon + carry; r->mon = (unsigned int) MODULO_RANGE(temp, 1, 13); r->year = r->year + (unsigned int) FQUOTIENT_RANGE(temp, 1, 13); if (r->year == 0) { if (temp < 1) r->year--; else r->year++; } } r->day = tempdays; /* * adjust the date/time type to the date values */ if (ret->type != XML_SCHEMAS_DATETIME) { if ((r->hour) || (r->min) || (r->sec)) ret->type = XML_SCHEMAS_DATETIME; else if (ret->type != XML_SCHEMAS_DATE) { if ((r->mon != 1) && (r->day != 1)) ret->type = XML_SCHEMAS_DATE; else if ((ret->type != XML_SCHEMAS_GYEARMONTH) && (r->mon != 1)) ret->type = XML_SCHEMAS_GYEARMONTH; } } xmlSchemaFreeValue(tmp); return ret; } /** * xmlSchemaDateNormalize: * @dt: an #xmlSchemaValPtr of a date/time type value. * @offset: number of seconds to adjust @dt by. * * Normalize @dt to GMT time. The @offset parameter is subtracted from * the return value is a time-zone offset is present on @dt. * * Returns a normalized copy of @dt or NULL if error. */ static xmlSchemaValPtr xmlSchemaDateNormalize (xmlSchemaValPtr dt, double offset) { xmlSchemaValPtr dur, ret; if (dt == NULL) return NULL; if (((dt->type != XML_SCHEMAS_TIME) && (dt->type != XML_SCHEMAS_DATETIME) && (dt->type != XML_SCHEMAS_DATE)) || (dt->value.date.tzo == 0)) return xmlSchemaDupVal(dt); dur = xmlSchemaNewValue(XML_SCHEMAS_DURATION); if (dur == NULL) return NULL; dur->value.date.sec -= offset; ret = _xmlSchemaDateAdd(dt, dur); if (ret == NULL) return NULL; xmlSchemaFreeValue(dur); /* ret->value.date.tzo = 0; */ return ret; } /** * _xmlSchemaDateCastYMToDays: * @dt: an #xmlSchemaValPtr * * Convert mon and year of @dt to total number of days. Take the * number of years since (or before) 1 AD and add the number of leap * years. This is a function because negative * years must be handled a little differently and there is no zero year. * * Returns number of days. */ static long _xmlSchemaDateCastYMToDays (const xmlSchemaValPtr dt) { long ret; int mon; mon = dt->value.date.mon; if (mon <= 0) mon = 1; /* normalization */ if (dt->value.date.year <= 0) ret = (dt->value.date.year * 365) + (((dt->value.date.year+1)/4)-((dt->value.date.year+1)/100)+ ((dt->value.date.year+1)/400)) + DAY_IN_YEAR(0, mon, dt->value.date.year); else ret = ((dt->value.date.year-1) * 365) + (((dt->value.date.year-1)/4)-((dt->value.date.year-1)/100)+ ((dt->value.date.year-1)/400)) + DAY_IN_YEAR(0, mon, dt->value.date.year); return ret; } /** * TIME_TO_NUMBER: * @dt: an #xmlSchemaValPtr * * Calculates the number of seconds in the time portion of @dt. * * Returns seconds. */ #define TIME_TO_NUMBER(dt) \ ((double)((dt->value.date.hour * SECS_PER_HOUR) + \ (dt->value.date.min * SECS_PER_MIN) + \ (dt->value.date.tzo * SECS_PER_MIN)) + \ dt->value.date.sec) /** * xmlSchemaCompareDates: * @x: a first date/time value * @y: a second date/time value * * Compare 2 date/times * * Returns -1 if x < y, 0 if x == y, 1 if x > y, 2 if x <> y, and -2 in * case of error */ static int xmlSchemaCompareDates (xmlSchemaValPtr x, xmlSchemaValPtr y) { unsigned char xmask, ymask, xor_mask, and_mask; xmlSchemaValPtr p1, p2, q1, q2; long p1d, p2d, q1d, q2d; if ((x == NULL) || (y == NULL)) return -2; if (x->value.date.tz_flag) { if (!y->value.date.tz_flag) { p1 = xmlSchemaDateNormalize(x, 0); p1d = _xmlSchemaDateCastYMToDays(p1) + p1->value.date.day; /* normalize y + 14:00 */ q1 = xmlSchemaDateNormalize(y, (14 * SECS_PER_HOUR)); q1d = _xmlSchemaDateCastYMToDays(q1) + q1->value.date.day; if (p1d < q1d) { xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); return -1; } else if (p1d == q1d) { double sec; sec = TIME_TO_NUMBER(p1) - TIME_TO_NUMBER(q1); if (sec < 0.0) { xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); return -1; } else { int ret = 0; /* normalize y - 14:00 */ q2 = xmlSchemaDateNormalize(y, -(14 * SECS_PER_HOUR)); q2d = _xmlSchemaDateCastYMToDays(q2) + q2->value.date.day; if (p1d > q2d) ret = 1; else if (p1d == q2d) { sec = TIME_TO_NUMBER(p1) - TIME_TO_NUMBER(q2); if (sec > 0.0) ret = 1; else ret = 2; /* indeterminate */ } xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); xmlSchemaFreeValue(q2); if (ret != 0) return(ret); } } else { xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); } } } else if (y->value.date.tz_flag) { q1 = xmlSchemaDateNormalize(y, 0); q1d = _xmlSchemaDateCastYMToDays(q1) + q1->value.date.day; /* normalize x - 14:00 */ p1 = xmlSchemaDateNormalize(x, -(14 * SECS_PER_HOUR)); p1d = _xmlSchemaDateCastYMToDays(p1) + p1->value.date.day; if (p1d < q1d) { xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); return -1; } else if (p1d == q1d) { double sec; sec = TIME_TO_NUMBER(p1) - TIME_TO_NUMBER(q1); if (sec < 0.0) { xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); return -1; } else { int ret = 0; /* normalize x + 14:00 */ p2 = xmlSchemaDateNormalize(x, (14 * SECS_PER_HOUR)); p2d = _xmlSchemaDateCastYMToDays(p2) + p2->value.date.day; if (p2d > q1d) { ret = 1; } else if (p2d == q1d) { sec = TIME_TO_NUMBER(p2) - TIME_TO_NUMBER(q1); if (sec > 0.0) ret = 1; else ret = 2; /* indeterminate */ } xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); xmlSchemaFreeValue(p2); if (ret != 0) return(ret); } } else { xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); } } /* * if the same type then calculate the difference */ if (x->type == y->type) { int ret = 0; q1 = xmlSchemaDateNormalize(y, 0); q1d = _xmlSchemaDateCastYMToDays(q1) + q1->value.date.day; p1 = xmlSchemaDateNormalize(x, 0); p1d = _xmlSchemaDateCastYMToDays(p1) + p1->value.date.day; if (p1d < q1d) { ret = -1; } else if (p1d > q1d) { ret = 1; } else { double sec; sec = TIME_TO_NUMBER(p1) - TIME_TO_NUMBER(q1); if (sec < 0.0) ret = -1; else if (sec > 0.0) ret = 1; } xmlSchemaFreeValue(p1); xmlSchemaFreeValue(q1); return(ret); } switch (x->type) { case XML_SCHEMAS_DATETIME: xmask = 0xf; break; case XML_SCHEMAS_DATE: xmask = 0x7; break; case XML_SCHEMAS_GYEAR: xmask = 0x1; break; case XML_SCHEMAS_GMONTH: xmask = 0x2; break; case XML_SCHEMAS_GDAY: xmask = 0x3; break; case XML_SCHEMAS_GYEARMONTH: xmask = 0x3; break; case XML_SCHEMAS_GMONTHDAY: xmask = 0x6; break; case XML_SCHEMAS_TIME: xmask = 0x8; break; default: xmask = 0; break; } switch (y->type) { case XML_SCHEMAS_DATETIME: ymask = 0xf; break; case XML_SCHEMAS_DATE: ymask = 0x7; break; case XML_SCHEMAS_GYEAR: ymask = 0x1; break; case XML_SCHEMAS_GMONTH: ymask = 0x2; break; case XML_SCHEMAS_GDAY: ymask = 0x3; break; case XML_SCHEMAS_GYEARMONTH: ymask = 0x3; break; case XML_SCHEMAS_GMONTHDAY: ymask = 0x6; break; case XML_SCHEMAS_TIME: ymask = 0x8; break; default: ymask = 0; break; } xor_mask = xmask ^ ymask; /* mark type differences */ and_mask = xmask & ymask; /* mark field specification */ /* year */ if (xor_mask & 1) return 2; /* indeterminate */ else if (and_mask & 1) { if (x->value.date.year < y->value.date.year) return -1; else if (x->value.date.year > y->value.date.year) return 1; } /* month */ if (xor_mask & 2) return 2; /* indeterminate */ else if (and_mask & 2) { if (x->value.date.mon < y->value.date.mon) return -1; else if (x->value.date.mon > y->value.date.mon) return 1; } /* day */ if (xor_mask & 4) return 2; /* indeterminate */ else if (and_mask & 4) { if (x->value.date.day < y->value.date.day) return -1; else if (x->value.date.day > y->value.date.day) return 1; } /* time */ if (xor_mask & 8) return 2; /* indeterminate */ else if (and_mask & 8) { if (x->value.date.hour < y->value.date.hour) return -1; else if (x->value.date.hour > y->value.date.hour) return 1; else if (x->value.date.min < y->value.date.min) return -1; else if (x->value.date.min > y->value.date.min) return 1; else if (x->value.date.sec < y->value.date.sec) return -1; else if (x->value.date.sec > y->value.date.sec) return 1; } return 0; } /** * xmlSchemaComparePreserveReplaceStrings: * @x: a first string value * @y: a second string value * @invert: inverts the result if x < y or x > y. * * Compare 2 string for their normalized values. * @x is a string with whitespace of "preserve", @y is * a string with a whitespace of "replace". I.e. @x could * be an "xsd:string" and @y an "xsd:normalizedString". * * Returns -1 if x < y, 0 if x == y, 1 if x > y, and -2 in * case of error */ static int xmlSchemaComparePreserveReplaceStrings(const xmlChar *x, const xmlChar *y, int invert) { int tmp; while ((*x != 0) && (*y != 0)) { if (IS_WSP_REPLACE_CH(*y)) { if (! IS_WSP_SPACE_CH(*x)) { if ((*x - 0x20) < 0) { if (invert) return(1); else return(-1); } else { if (invert) return(-1); else return(1); } } } else { tmp = *x - *y; if (tmp < 0) { if (invert) return(1); else return(-1); } if (tmp > 0) { if (invert) return(-1); else return(1); } } x++; y++; } if (*x != 0) { if (invert) return(-1); else return(1); } if (*y != 0) { if (invert) return(1); else return(-1); } return(0); } /** * xmlSchemaComparePreserveCollapseStrings: * @x: a first string value * @y: a second string value * * Compare 2 string for their normalized values. * @x is a string with whitespace of "preserve", @y is * a string with a whitespace of "collapse". I.e. @x could * be an "xsd:string" and @y an "xsd:normalizedString". * * Returns -1 if x < y, 0 if x == y, 1 if x > y, and -2 in * case of error */ static int xmlSchemaComparePreserveCollapseStrings(const xmlChar *x, const xmlChar *y, int invert) { int tmp; /* * Skip leading blank chars of the collapsed string. */ while IS_WSP_BLANK_CH(*y) y++; while ((*x != 0) && (*y != 0)) { if IS_WSP_BLANK_CH(*y) { if (! IS_WSP_SPACE_CH(*x)) { /* * The yv character would have been replaced to 0x20. */ if ((*x - 0x20) < 0) { if (invert) return(1); else return(-1); } else { if (invert) return(-1); else return(1); } } x++; y++; /* * Skip contiguous blank chars of the collapsed string. */ while IS_WSP_BLANK_CH(*y) y++; } else { tmp = *x++ - *y++; if (tmp < 0) { if (invert) return(1); else return(-1); } if (tmp > 0) { if (invert) return(-1); else return(1); } } } if (*x != 0) { if (invert) return(-1); else return(1); } if (*y != 0) { /* * Skip trailing blank chars of the collapsed string. */ while IS_WSP_BLANK_CH(*y) y++; if (*y != 0) { if (invert) return(1); else return(-1); } } return(0); } /** * xmlSchemaComparePreserveCollapseStrings: * @x: a first string value * @y: a second string value * * Compare 2 string for their normalized values. * @x is a string with whitespace of "preserve", @y is * a string with a whitespace of "collapse". I.e. @x could * be an "xsd:string" and @y an "xsd:normalizedString". * * Returns -1 if x < y, 0 if x == y, 1 if x > y, and -2 in * case of error */ static int xmlSchemaCompareReplaceCollapseStrings(const xmlChar *x, const xmlChar *y, int invert) { int tmp; /* * Skip leading blank chars of the collapsed string. */ while IS_WSP_BLANK_CH(*y) y++; while ((*x != 0) && (*y != 0)) { if IS_WSP_BLANK_CH(*y) { if (! IS_WSP_BLANK_CH(*x)) { /* * The yv character would have been replaced to 0x20. */ if ((*x - 0x20) < 0) { if (invert) return(1); else return(-1); } else { if (invert) return(-1); else return(1); } } x++; y++; /* * Skip contiguous blank chars of the collapsed string. */ while IS_WSP_BLANK_CH(*y) y++; } else { if IS_WSP_BLANK_CH(*x) { /* * The xv character would have been replaced to 0x20. */ if ((0x20 - *y) < 0) { if (invert) return(1); else return(-1); } else { if (invert) return(-1); else return(1); } } tmp = *x++ - *y++; if (tmp < 0) return(-1); if (tmp > 0) return(1); } } if (*x != 0) { if (invert) return(-1); else return(1); } if (*y != 0) { /* * Skip trailing blank chars of the collapsed string. */ while IS_WSP_BLANK_CH(*y) y++; if (*y != 0) { if (invert) return(1); else return(-1); } } return(0); } /** * xmlSchemaCompareReplacedStrings: * @x: a first string value * @y: a second string value * * Compare 2 string for their normalized values. * * Returns -1 if x < y, 0 if x == y, 1 if x > y, and -2 in * case of error */ static int xmlSchemaCompareReplacedStrings(const xmlChar *x, const xmlChar *y) { int tmp; while ((*x != 0) && (*y != 0)) { if IS_WSP_BLANK_CH(*y) { if (! IS_WSP_BLANK_CH(*x)) { if ((*x - 0x20) < 0) return(-1); else return(1); } } else { if IS_WSP_BLANK_CH(*x) { if ((0x20 - *y) < 0) return(-1); else return(1); } tmp = *x - *y; if (tmp < 0) return(-1); if (tmp > 0) return(1); } x++; y++; } if (*x != 0) return(1); if (*y != 0) return(-1); return(0); } /** * xmlSchemaCompareNormStrings: * @x: a first string value * @y: a second string value * * Compare 2 string for their normalized values. * * Returns -1 if x < y, 0 if x == y, 1 if x > y, and -2 in * case of error */ static int xmlSchemaCompareNormStrings(const xmlChar *x, const xmlChar *y) { int tmp; while (IS_BLANK_CH(*x)) x++; while (IS_BLANK_CH(*y)) y++; while ((*x != 0) && (*y != 0)) { if (IS_BLANK_CH(*x)) { if (!IS_BLANK_CH(*y)) { tmp = *x - *y; return(tmp); } while (IS_BLANK_CH(*x)) x++; while (IS_BLANK_CH(*y)) y++; } else { tmp = *x++ - *y++; if (tmp < 0) return(-1); if (tmp > 0) return(1); } } if (*x != 0) { while (IS_BLANK_CH(*x)) x++; if (*x != 0) return(1); } if (*y != 0) { while (IS_BLANK_CH(*y)) y++; if (*y != 0) return(-1); } return(0); } /** * xmlSchemaCompareFloats: * @x: a first float or double value * @y: a second float or double value * * Compare 2 values * * Returns -1 if x < y, 0 if x == y, 1 if x > y, 2 if x <> y, and -2 in * case of error */ static int xmlSchemaCompareFloats(xmlSchemaValPtr x, xmlSchemaValPtr y) { double d1, d2; if ((x == NULL) || (y == NULL)) return(-2); /* * Cast everything to doubles. */ if (x->type == XML_SCHEMAS_DOUBLE) d1 = x->value.d; else if (x->type == XML_SCHEMAS_FLOAT) d1 = x->value.f; else return(-2); if (y->type == XML_SCHEMAS_DOUBLE) d2 = y->value.d; else if (y->type == XML_SCHEMAS_FLOAT) d2 = y->value.f; else return(-2); /* * Check for special cases. */ if (xmlXPathIsNaN(d1)) { if (xmlXPathIsNaN(d2)) return(0); return(1); } if (xmlXPathIsNaN(d2)) return(-1); if (d1 == xmlXPathPINF) { if (d2 == xmlXPathPINF) return(0); return(1); } if (d2 == xmlXPathPINF) return(-1); if (d1 == xmlXPathNINF) { if (d2 == xmlXPathNINF) return(0); return(-1); } if (d2 == xmlXPathNINF) return(1); /* * basic tests, the last one we should have equality, but * portability is more important than speed and handling * NaN or Inf in a portable way is always a challenge, so ... */ if (d1 < d2) return(-1); if (d1 > d2) return(1); if (d1 == d2) return(0); return(2); } /** * xmlSchemaCompareValues: * @x: a first value * @xvalue: the first value as a string (optional) * @xwtsp: the whitespace type * @y: a second value * @xvalue: the second value as a string (optional) * @ywtsp: the whitespace type * * Compare 2 values * * Returns -1 if x < y, 0 if x == y, 1 if x > y, 2 if x <> y, 3 if not * comparable and -2 in case of error */ static int xmlSchemaCompareValuesInternal(xmlSchemaValType xtype, xmlSchemaValPtr x, const xmlChar *xvalue, xmlSchemaWhitespaceValueType xws, xmlSchemaValType ytype, xmlSchemaValPtr y, const xmlChar *yvalue, xmlSchemaWhitespaceValueType yws) { switch (xtype) { case XML_SCHEMAS_UNKNOWN: case XML_SCHEMAS_ANYTYPE: return(-2); case XML_SCHEMAS_INTEGER: case XML_SCHEMAS_NPINTEGER: case XML_SCHEMAS_NINTEGER: case XML_SCHEMAS_NNINTEGER: case XML_SCHEMAS_PINTEGER: case XML_SCHEMAS_INT: case XML_SCHEMAS_UINT: case XML_SCHEMAS_LONG: case XML_SCHEMAS_ULONG: case XML_SCHEMAS_SHORT: case XML_SCHEMAS_USHORT: case XML_SCHEMAS_BYTE: case XML_SCHEMAS_UBYTE: case XML_SCHEMAS_DECIMAL: if ((x == NULL) || (y == NULL)) return(-2); if (ytype == xtype) return(xmlSchemaCompareDecimals(x, y)); if ((ytype == XML_SCHEMAS_DECIMAL) || (ytype == XML_SCHEMAS_INTEGER) || (ytype == XML_SCHEMAS_NPINTEGER) || (ytype == XML_SCHEMAS_NINTEGER) || (ytype == XML_SCHEMAS_NNINTEGER) || (ytype == XML_SCHEMAS_PINTEGER) || (ytype == XML_SCHEMAS_INT) || (ytype == XML_SCHEMAS_UINT) || (ytype == XML_SCHEMAS_LONG) || (ytype == XML_SCHEMAS_ULONG) || (ytype == XML_SCHEMAS_SHORT) || (ytype == XML_SCHEMAS_USHORT) || (ytype == XML_SCHEMAS_BYTE) || (ytype == XML_SCHEMAS_UBYTE)) return(xmlSchemaCompareDecimals(x, y)); return(-2); case XML_SCHEMAS_DURATION: if ((x == NULL) || (y == NULL)) return(-2); if (ytype == XML_SCHEMAS_DURATION) return(xmlSchemaCompareDurations(x, y)); return(-2); case XML_SCHEMAS_TIME: case XML_SCHEMAS_GDAY: case XML_SCHEMAS_GMONTH: case XML_SCHEMAS_GMONTHDAY: case XML_SCHEMAS_GYEAR: case XML_SCHEMAS_GYEARMONTH: case XML_SCHEMAS_DATE: case XML_SCHEMAS_DATETIME: if ((x == NULL) || (y == NULL)) return(-2); if ((ytype == XML_SCHEMAS_DATETIME) || (ytype == XML_SCHEMAS_TIME) || (ytype == XML_SCHEMAS_GDAY) || (ytype == XML_SCHEMAS_GMONTH) || (ytype == XML_SCHEMAS_GMONTHDAY) || (ytype == XML_SCHEMAS_GYEAR) || (ytype == XML_SCHEMAS_DATE) || (ytype == XML_SCHEMAS_GYEARMONTH)) return (xmlSchemaCompareDates(x, y)); return (-2); /* * Note that we will support comparison of string types against * anySimpleType as well. */ case XML_SCHEMAS_ANYSIMPLETYPE: case XML_SCHEMAS_STRING: case XML_SCHEMAS_NORMSTRING: case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: case XML_SCHEMAS_NMTOKEN: case XML_SCHEMAS_NAME: case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_ID: case XML_SCHEMAS_IDREF: case XML_SCHEMAS_ENTITY: case XML_SCHEMAS_ANYURI: { const xmlChar *xv, *yv; if (x == NULL) xv = xvalue; else xv = x->value.str; if (y == NULL) yv = yvalue; else yv = y->value.str; /* * TODO: Compare those against QName. */ if (ytype == XML_SCHEMAS_QNAME) { TODO if (y == NULL) return(-2); return (-2); } if ((ytype == XML_SCHEMAS_ANYSIMPLETYPE) || (ytype == XML_SCHEMAS_STRING) || (ytype == XML_SCHEMAS_NORMSTRING) || (ytype == XML_SCHEMAS_TOKEN) || (ytype == XML_SCHEMAS_LANGUAGE) || (ytype == XML_SCHEMAS_NMTOKEN) || (ytype == XML_SCHEMAS_NAME) || (ytype == XML_SCHEMAS_NCNAME) || (ytype == XML_SCHEMAS_ID) || (ytype == XML_SCHEMAS_IDREF) || (ytype == XML_SCHEMAS_ENTITY) || (ytype == XML_SCHEMAS_ANYURI)) { if (xws == XML_SCHEMA_WHITESPACE_PRESERVE) { if (yws == XML_SCHEMA_WHITESPACE_PRESERVE) { /* TODO: What about x < y or x > y. */ if (xmlStrEqual(xv, yv)) return (0); else return (2); } else if (yws == XML_SCHEMA_WHITESPACE_REPLACE) return (xmlSchemaComparePreserveReplaceStrings(xv, yv, 0)); else if (yws == XML_SCHEMA_WHITESPACE_COLLAPSE) return (xmlSchemaComparePreserveCollapseStrings(xv, yv, 0)); } else if (xws == XML_SCHEMA_WHITESPACE_REPLACE) { if (yws == XML_SCHEMA_WHITESPACE_PRESERVE) return (xmlSchemaComparePreserveReplaceStrings(yv, xv, 1)); if (yws == XML_SCHEMA_WHITESPACE_REPLACE) return (xmlSchemaCompareReplacedStrings(xv, yv)); if (yws == XML_SCHEMA_WHITESPACE_COLLAPSE) return (xmlSchemaCompareReplaceCollapseStrings(xv, yv, 0)); } else if (xws == XML_SCHEMA_WHITESPACE_COLLAPSE) { if (yws == XML_SCHEMA_WHITESPACE_PRESERVE) return (xmlSchemaComparePreserveCollapseStrings(yv, xv, 1)); if (yws == XML_SCHEMA_WHITESPACE_REPLACE) return (xmlSchemaCompareReplaceCollapseStrings(yv, xv, 1)); if (yws == XML_SCHEMA_WHITESPACE_COLLAPSE) return (xmlSchemaCompareNormStrings(xv, yv)); } else return (-2); } return (-2); } case XML_SCHEMAS_QNAME: case XML_SCHEMAS_NOTATION: if ((x == NULL) || (y == NULL)) return(-2); if ((ytype == XML_SCHEMAS_QNAME) || (ytype == XML_SCHEMAS_NOTATION)) { if ((xmlStrEqual(x->value.qname.name, y->value.qname.name)) && (xmlStrEqual(x->value.qname.uri, y->value.qname.uri))) return(0); return(2); } return (-2); case XML_SCHEMAS_FLOAT: case XML_SCHEMAS_DOUBLE: if ((x == NULL) || (y == NULL)) return(-2); if ((ytype == XML_SCHEMAS_FLOAT) || (ytype == XML_SCHEMAS_DOUBLE)) return (xmlSchemaCompareFloats(x, y)); return (-2); case XML_SCHEMAS_BOOLEAN: if ((x == NULL) || (y == NULL)) return(-2); if (ytype == XML_SCHEMAS_BOOLEAN) { if (x->value.b == y->value.b) return(0); if (x->value.b == 0) return(-1); return(1); } return (-2); case XML_SCHEMAS_HEXBINARY: if ((x == NULL) || (y == NULL)) return(-2); if (ytype == XML_SCHEMAS_HEXBINARY) { if (x->value.hex.total == y->value.hex.total) { int ret = xmlStrcmp(x->value.hex.str, y->value.hex.str); if (ret > 0) return(1); else if (ret == 0) return(0); } else if (x->value.hex.total > y->value.hex.total) return(1); return(-1); } return (-2); case XML_SCHEMAS_BASE64BINARY: if ((x == NULL) || (y == NULL)) return(-2); if (ytype == XML_SCHEMAS_BASE64BINARY) { if (x->value.base64.total == y->value.base64.total) { int ret = xmlStrcmp(x->value.base64.str, y->value.base64.str); if (ret > 0) return(1); else if (ret == 0) return(0); else return(-1); } else if (x->value.base64.total > y->value.base64.total) return(1); else return(-1); } return (-2); case XML_SCHEMAS_IDREFS: case XML_SCHEMAS_ENTITIES: case XML_SCHEMAS_NMTOKENS: TODO break; } return -2; } /** * xmlSchemaCompareValues: * @x: a first value * @y: a second value * * Compare 2 values * * Returns -1 if x < y, 0 if x == y, 1 if x > y, 2 if x <> y, and -2 in * case of error */ int xmlSchemaCompareValues(xmlSchemaValPtr x, xmlSchemaValPtr y) { xmlSchemaWhitespaceValueType xws, yws; if ((x == NULL) || (y == NULL)) return(-2); if (x->type == XML_SCHEMAS_STRING) xws = XML_SCHEMA_WHITESPACE_PRESERVE; else if (x->type == XML_SCHEMAS_NORMSTRING) xws = XML_SCHEMA_WHITESPACE_REPLACE; else xws = XML_SCHEMA_WHITESPACE_COLLAPSE; if (y->type == XML_SCHEMAS_STRING) yws = XML_SCHEMA_WHITESPACE_PRESERVE; else if (x->type == XML_SCHEMAS_NORMSTRING) yws = XML_SCHEMA_WHITESPACE_REPLACE; else yws = XML_SCHEMA_WHITESPACE_COLLAPSE; return(xmlSchemaCompareValuesInternal(x->type, x, NULL, xws, y->type, y, NULL, yws)); } /** * xmlSchemaCompareValuesWhtsp: * @x: a first value * @xws: the whitespace value of x * @y: a second value * @yws: the whitespace value of y * * Compare 2 values * * Returns -1 if x < y, 0 if x == y, 1 if x > y, 2 if x <> y, and -2 in * case of error */ int xmlSchemaCompareValuesWhtsp(xmlSchemaValPtr x, xmlSchemaWhitespaceValueType xws, xmlSchemaValPtr y, xmlSchemaWhitespaceValueType yws) { if ((x == NULL) || (y == NULL)) return(-2); return(xmlSchemaCompareValuesInternal(x->type, x, NULL, xws, y->type, y, NULL, yws)); } /** * xmlSchemaCompareValuesWhtspExt: * @x: a first value * @xws: the whitespace value of x * @y: a second value * @yws: the whitespace value of y * * Compare 2 values * * Returns -1 if x < y, 0 if x == y, 1 if x > y, 2 if x <> y, and -2 in * case of error */ static int xmlSchemaCompareValuesWhtspExt(xmlSchemaValType xtype, xmlSchemaValPtr x, const xmlChar *xvalue, xmlSchemaWhitespaceValueType xws, xmlSchemaValType ytype, xmlSchemaValPtr y, const xmlChar *yvalue, xmlSchemaWhitespaceValueType yws) { return(xmlSchemaCompareValuesInternal(xtype, x, xvalue, xws, ytype, y, yvalue, yws)); } /** * xmlSchemaNormLen: * @value: a string * * Computes the UTF8 length of the normalized value of the string * * Returns the length or -1 in case of error. */ static int xmlSchemaNormLen(const xmlChar *value) { const xmlChar *utf; int ret = 0; if (value == NULL) return(-1); utf = value; while (IS_BLANK_CH(*utf)) utf++; while (*utf != 0) { if (utf[0] & 0x80) { if ((utf[1] & 0xc0) != 0x80) return(-1); if ((utf[0] & 0xe0) == 0xe0) { if ((utf[2] & 0xc0) != 0x80) return(-1); if ((utf[0] & 0xf0) == 0xf0) { if ((utf[0] & 0xf8) != 0xf0 || (utf[3] & 0xc0) != 0x80) return(-1); utf += 4; } else { utf += 3; } } else { utf += 2; } } else if (IS_BLANK_CH(*utf)) { while (IS_BLANK_CH(*utf)) utf++; if (*utf == 0) break; } else { utf++; } ret++; } return(ret); } /** * xmlSchemaGetFacetValueAsULong: * @facet: an schemas type facet * * Extract the value of a facet * * Returns the value as a long */ unsigned long xmlSchemaGetFacetValueAsULong(xmlSchemaFacetPtr facet) { /* * TODO: Check if this is a decimal. */ if (facet == NULL) return 0; return ((unsigned long) facet->val->value.decimal.lo); } /** * xmlSchemaValidateListSimpleTypeFacet: * @facet: the facet to check * @value: the lexical repr of the value to validate * @actualLen: the number of list items * @expectedLen: the resulting expected number of list items * * Checks the value of a list simple type against a facet. * * Returns 0 if the value is valid, a positive error code * number otherwise and -1 in case of an internal error. */ int xmlSchemaValidateListSimpleTypeFacet(xmlSchemaFacetPtr facet, const xmlChar *value, unsigned long actualLen, unsigned long *expectedLen) { if (facet == NULL) return(-1); /* * TODO: Check if this will work with large numbers. * (compare value.decimal.mi and value.decimal.hi as well?). */ if (facet->type == XML_SCHEMA_FACET_LENGTH) { if (actualLen != facet->val->value.decimal.lo) { if (expectedLen != NULL) *expectedLen = facet->val->value.decimal.lo; return (XML_SCHEMAV_CVC_LENGTH_VALID); } } else if (facet->type == XML_SCHEMA_FACET_MINLENGTH) { if (actualLen < facet->val->value.decimal.lo) { if (expectedLen != NULL) *expectedLen = facet->val->value.decimal.lo; return (XML_SCHEMAV_CVC_MINLENGTH_VALID); } } else if (facet->type == XML_SCHEMA_FACET_MAXLENGTH) { if (actualLen > facet->val->value.decimal.lo) { if (expectedLen != NULL) *expectedLen = facet->val->value.decimal.lo; return (XML_SCHEMAV_CVC_MAXLENGTH_VALID); } } else /* * NOTE: That we can pass NULL as xmlSchemaValPtr to * xmlSchemaValidateFacet, since the remaining facet types * are: XML_SCHEMA_FACET_PATTERN, XML_SCHEMA_FACET_ENUMERATION. */ return(xmlSchemaValidateFacet(NULL, facet, value, NULL)); return (0); } /** * xmlSchemaValidateLengthFacet: * @type: the built-in type * @facet: the facet to check * @value: the lexical repr. of the value to be validated * @val: the precomputed value * @ws: the whitespace type of the value * @length: the actual length of the value * * Checka a value against a "length", "minLength" and "maxLength" * facet; sets @length to the computed length of @value. * * Returns 0 if the value is valid, a positive error code * otherwise and -1 in case of an internal or API error. */ static int xmlSchemaValidateLengthFacetInternal(xmlSchemaFacetPtr facet, xmlSchemaTypeType valType, const xmlChar *value, xmlSchemaValPtr val, unsigned long *length, xmlSchemaWhitespaceValueType ws) { unsigned int len = 0; if ((length == NULL) || (facet == NULL)) return (-1); *length = 0; if ((facet->type != XML_SCHEMA_FACET_LENGTH) && (facet->type != XML_SCHEMA_FACET_MAXLENGTH) && (facet->type != XML_SCHEMA_FACET_MINLENGTH)) return (-1); /* * TODO: length, maxLength and minLength must be of type * nonNegativeInteger only. Check if decimal is used somehow. */ if ((facet->val == NULL) || ((facet->val->type != XML_SCHEMAS_DECIMAL) && (facet->val->type != XML_SCHEMAS_NNINTEGER)) || (facet->val->value.decimal.frac != 0)) { return(-1); } if ((val != NULL) && (val->type == XML_SCHEMAS_HEXBINARY)) len = val->value.hex.total; else if ((val != NULL) && (val->type == XML_SCHEMAS_BASE64BINARY)) len = val->value.base64.total; else { switch (valType) { case XML_SCHEMAS_STRING: case XML_SCHEMAS_NORMSTRING: if (ws == XML_SCHEMA_WHITESPACE_UNKNOWN) { /* * This is to ensure API compatibility with the old * xmlSchemaValidateLengthFacet(). Anyway, this was and * is not the correct handling. * TODO: Get rid of this case somehow. */ if (valType == XML_SCHEMAS_STRING) len = xmlUTF8Strlen(value); else len = xmlSchemaNormLen(value); } else if (value != NULL) { if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) len = xmlSchemaNormLen(value); else /* * Should be OK for "preserve" as well. */ len = xmlUTF8Strlen(value); } break; case XML_SCHEMAS_IDREF: case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: case XML_SCHEMAS_NMTOKEN: case XML_SCHEMAS_NAME: case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_ID: /* * FIXME: What exactly to do with anyURI? */ case XML_SCHEMAS_ANYURI: if (value != NULL) len = xmlSchemaNormLen(value); break; case XML_SCHEMAS_QNAME: case XML_SCHEMAS_NOTATION: /* * For QName and NOTATION, those facets are * deprecated and should be ignored. */ return (0); default: TODO } } *length = (unsigned long) len; /* * TODO: Return the whole expected value, i.e. "lo", "mi" and "hi". */ if (facet->type == XML_SCHEMA_FACET_LENGTH) { if (len != facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_LENGTH_VALID); } else if (facet->type == XML_SCHEMA_FACET_MINLENGTH) { if (len < facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_MINLENGTH_VALID); } else { if (len > facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_MAXLENGTH_VALID); } return (0); } /** * xmlSchemaValidateLengthFacet: * @type: the built-in type * @facet: the facet to check * @value: the lexical repr. of the value to be validated * @val: the precomputed value * @length: the actual length of the value * * Checka a value against a "length", "minLength" and "maxLength" * facet; sets @length to the computed length of @value. * * Returns 0 if the value is valid, a positive error code * otherwise and -1 in case of an internal or API error. */ int xmlSchemaValidateLengthFacet(xmlSchemaTypePtr type, xmlSchemaFacetPtr facet, const xmlChar *value, xmlSchemaValPtr val, unsigned long *length) { if (type == NULL) return(-1); return (xmlSchemaValidateLengthFacetInternal(facet, type->builtInType, value, val, length, XML_SCHEMA_WHITESPACE_UNKNOWN)); } /** * xmlSchemaValidateLengthFacetWhtsp: * @facet: the facet to check * @valType: the built-in type * @value: the lexical repr. of the value to be validated * @val: the precomputed value * @ws: the whitespace type of the value * @length: the actual length of the value * * Checka a value against a "length", "minLength" and "maxLength" * facet; sets @length to the computed length of @value. * * Returns 0 if the value is valid, a positive error code * otherwise and -1 in case of an internal or API error. */ int xmlSchemaValidateLengthFacetWhtsp(xmlSchemaFacetPtr facet, xmlSchemaValType valType, const xmlChar *value, xmlSchemaValPtr val, unsigned long *length, xmlSchemaWhitespaceValueType ws) { return (xmlSchemaValidateLengthFacetInternal(facet, valType, value, val, length, ws)); } /** * xmlSchemaValidateFacetInternal: * @facet: the facet to check * @fws: the whitespace type of the facet's value * @valType: the built-in type of the value * @value: the lexical repr of the value to validate * @val: the precomputed value * @ws: the whitespace type of the value * * Check a value against a facet condition * * Returns 0 if the element is schemas valid, a positive error code * number otherwise and -1 in case of internal or API error. */ static int xmlSchemaValidateFacetInternal(xmlSchemaFacetPtr facet, xmlSchemaWhitespaceValueType fws, xmlSchemaValType valType, const xmlChar *value, xmlSchemaValPtr val, xmlSchemaWhitespaceValueType ws) { int ret; if (facet == NULL) return(-1); switch (facet->type) { case XML_SCHEMA_FACET_PATTERN: /* * NOTE that for patterns, the @value needs to be the normalized * value, *not* the lexical initial value or the canonical value. */ if (value == NULL) return(-1); ret = xmlRegexpExec(facet->regexp, value); if (ret == 1) return(0); if (ret == 0) return(XML_SCHEMAV_CVC_PATTERN_VALID); return(ret); case XML_SCHEMA_FACET_MAXEXCLUSIVE: ret = xmlSchemaCompareValues(val, facet->val); if (ret == -2) return(-1); if (ret == -1) return(0); return(XML_SCHEMAV_CVC_MAXEXCLUSIVE_VALID); case XML_SCHEMA_FACET_MAXINCLUSIVE: ret = xmlSchemaCompareValues(val, facet->val); if (ret == -2) return(-1); if ((ret == -1) || (ret == 0)) return(0); return(XML_SCHEMAV_CVC_MAXINCLUSIVE_VALID); case XML_SCHEMA_FACET_MINEXCLUSIVE: ret = xmlSchemaCompareValues(val, facet->val); if (ret == -2) return(-1); if (ret == 1) return(0); return(XML_SCHEMAV_CVC_MINEXCLUSIVE_VALID); case XML_SCHEMA_FACET_MININCLUSIVE: ret = xmlSchemaCompareValues(val, facet->val); if (ret == -2) return(-1); if ((ret == 1) || (ret == 0)) return(0); return(XML_SCHEMAV_CVC_MININCLUSIVE_VALID); case XML_SCHEMA_FACET_WHITESPACE: /* TODO whitespaces */ /* * NOTE: Whitespace should be handled to normalize * the value to be validated against a the facets; * not to normalize the value in-between. */ return(0); case XML_SCHEMA_FACET_ENUMERATION: if (ws == XML_SCHEMA_WHITESPACE_UNKNOWN) { /* * This is to ensure API compatibility with the old * xmlSchemaValidateFacet(). * TODO: Get rid of this case. */ if ((facet->value != NULL) && (xmlStrEqual(facet->value, value))) return(0); } else { ret = xmlSchemaCompareValuesWhtspExt(facet->val->type, facet->val, facet->value, fws, valType, val, value, ws); if (ret == -2) return(-1); if (ret == 0) return(0); } return(XML_SCHEMAV_CVC_ENUMERATION_VALID); case XML_SCHEMA_FACET_LENGTH: /* * SPEC (1.3) "if {primitive type definition} is QName or NOTATION, * then any {value} is facet-valid." */ if ((valType == XML_SCHEMAS_QNAME) || (valType == XML_SCHEMAS_NOTATION)) return (0); /* No break on purpose. */ case XML_SCHEMA_FACET_MAXLENGTH: case XML_SCHEMA_FACET_MINLENGTH: { unsigned int len = 0; if ((valType == XML_SCHEMAS_QNAME) || (valType == XML_SCHEMAS_NOTATION)) return (0); /* * TODO: length, maxLength and minLength must be of type * nonNegativeInteger only. Check if decimal is used somehow. */ if ((facet->val == NULL) || ((facet->val->type != XML_SCHEMAS_DECIMAL) && (facet->val->type != XML_SCHEMAS_NNINTEGER)) || (facet->val->value.decimal.frac != 0)) { return(-1); } if ((val != NULL) && (val->type == XML_SCHEMAS_HEXBINARY)) len = val->value.hex.total; else if ((val != NULL) && (val->type == XML_SCHEMAS_BASE64BINARY)) len = val->value.base64.total; else { switch (valType) { case XML_SCHEMAS_STRING: case XML_SCHEMAS_NORMSTRING: if (ws == XML_SCHEMA_WHITESPACE_UNKNOWN) { /* * This is to ensure API compatibility with the old * xmlSchemaValidateFacet(). Anyway, this was and * is not the correct handling. * TODO: Get rid of this case somehow. */ if (valType == XML_SCHEMAS_STRING) len = xmlUTF8Strlen(value); else len = xmlSchemaNormLen(value); } else if (value != NULL) { if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) len = xmlSchemaNormLen(value); else /* * Should be OK for "preserve" as well. */ len = xmlUTF8Strlen(value); } break; case XML_SCHEMAS_IDREF: case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: case XML_SCHEMAS_NMTOKEN: case XML_SCHEMAS_NAME: case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_ID: case XML_SCHEMAS_ANYURI: if (value != NULL) len = xmlSchemaNormLen(value); break; default: TODO } } if (facet->type == XML_SCHEMA_FACET_LENGTH) { if (len != facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_LENGTH_VALID); } else if (facet->type == XML_SCHEMA_FACET_MINLENGTH) { if (len < facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_MINLENGTH_VALID); } else { if (len > facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_MAXLENGTH_VALID); } break; } case XML_SCHEMA_FACET_TOTALDIGITS: case XML_SCHEMA_FACET_FRACTIONDIGITS: if ((facet->val == NULL) || ((facet->val->type != XML_SCHEMAS_PINTEGER) && (facet->val->type != XML_SCHEMAS_NNINTEGER)) || (facet->val->value.decimal.frac != 0)) { return(-1); } if ((val == NULL) || ((val->type != XML_SCHEMAS_DECIMAL) && (val->type != XML_SCHEMAS_INTEGER) && (val->type != XML_SCHEMAS_NPINTEGER) && (val->type != XML_SCHEMAS_NINTEGER) && (val->type != XML_SCHEMAS_NNINTEGER) && (val->type != XML_SCHEMAS_PINTEGER) && (val->type != XML_SCHEMAS_INT) && (val->type != XML_SCHEMAS_UINT) && (val->type != XML_SCHEMAS_LONG) && (val->type != XML_SCHEMAS_ULONG) && (val->type != XML_SCHEMAS_SHORT) && (val->type != XML_SCHEMAS_USHORT) && (val->type != XML_SCHEMAS_BYTE) && (val->type != XML_SCHEMAS_UBYTE))) { return(-1); } if (facet->type == XML_SCHEMA_FACET_TOTALDIGITS) { if (val->value.decimal.total > facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_TOTALDIGITS_VALID); } else if (facet->type == XML_SCHEMA_FACET_FRACTIONDIGITS) { if (val->value.decimal.frac > facet->val->value.decimal.lo) return(XML_SCHEMAV_CVC_FRACTIONDIGITS_VALID); } break; default: TODO } return(0); } /** * xmlSchemaValidateFacet: * @base: the base type * @facet: the facet to check * @value: the lexical repr of the value to validate * @val: the precomputed value * * Check a value against a facet condition * * Returns 0 if the element is schemas valid, a positive error code * number otherwise and -1 in case of internal or API error. */ int xmlSchemaValidateFacet(xmlSchemaTypePtr base, xmlSchemaFacetPtr facet, const xmlChar *value, xmlSchemaValPtr val) { /* * This tries to ensure API compatibility regarding the old * xmlSchemaValidateFacet() and the new xmlSchemaValidateFacetInternal() and * xmlSchemaValidateFacetWhtsp(). */ if (val != NULL) return(xmlSchemaValidateFacetInternal(facet, XML_SCHEMA_WHITESPACE_UNKNOWN, val->type, value, val, XML_SCHEMA_WHITESPACE_UNKNOWN)); else if (base != NULL) return(xmlSchemaValidateFacetInternal(facet, XML_SCHEMA_WHITESPACE_UNKNOWN, base->builtInType, value, val, XML_SCHEMA_WHITESPACE_UNKNOWN)); return(-1); } /** * xmlSchemaValidateFacetWhtsp: * @facet: the facet to check * @fws: the whitespace type of the facet's value * @valType: the built-in type of the value * @value: the lexical (or normalized for pattern) repr of the value to validate * @val: the precomputed value * @ws: the whitespace type of the value * * Check a value against a facet condition. This takes value normalization * according to the specified whitespace types into account. * Note that @value needs to be the *normalized* value if the facet * is of type "pattern". * * Returns 0 if the element is schemas valid, a positive error code * number otherwise and -1 in case of internal or API error. */ int xmlSchemaValidateFacetWhtsp(xmlSchemaFacetPtr facet, xmlSchemaWhitespaceValueType fws, xmlSchemaValType valType, const xmlChar *value, xmlSchemaValPtr val, xmlSchemaWhitespaceValueType ws) { return(xmlSchemaValidateFacetInternal(facet, fws, valType, value, val, ws)); } #if 0 #ifndef DBL_DIG #define DBL_DIG 16 #endif #ifndef DBL_EPSILON #define DBL_EPSILON 1E-9 #endif #define INTEGER_DIGITS DBL_DIG #define FRACTION_DIGITS (DBL_DIG + 1) #define EXPONENT_DIGITS (3 + 2) /** * xmlXPathFormatNumber: * @number: number to format * @buffer: output buffer * @buffersize: size of output buffer * * Convert the number into a string representation. */ static void xmlSchemaFormatFloat(double number, char buffer[], int buffersize) { switch (xmlXPathIsInf(number)) { case 1: if (buffersize > (int)sizeof("INF")) snprintf(buffer, buffersize, "INF"); break; case -1: if (buffersize > (int)sizeof("-INF")) snprintf(buffer, buffersize, "-INF"); break; default: if (xmlXPathIsNaN(number)) { if (buffersize > (int)sizeof("NaN")) snprintf(buffer, buffersize, "NaN"); } else if (number == 0) { snprintf(buffer, buffersize, "0.0E0"); } else { /* 3 is sign, decimal point, and terminating zero */ char work[DBL_DIG + EXPONENT_DIGITS + 3]; int integer_place, fraction_place; char *ptr; char *after_fraction; double absolute_value; int size; absolute_value = fabs(number); /* * Result is in work, and after_fraction points * just past the fractional part. * Use scientific notation */ integer_place = DBL_DIG + EXPONENT_DIGITS + 1; fraction_place = DBL_DIG - 1; snprintf(work, sizeof(work),"%*.*e", integer_place, fraction_place, number); after_fraction = strchr(work + DBL_DIG, 'e'); /* Remove fractional trailing zeroes */ ptr = after_fraction; while (*(--ptr) == '0') ; if (*ptr != '.') ptr++; while ((*ptr++ = *after_fraction++) != 0); /* Finally copy result back to caller */ size = strlen(work) + 1; if (size > buffersize) { work[buffersize - 1] = 0; size = buffersize; } memmove(buffer, work, size); } break; } } #endif /** * xmlSchemaGetCanonValue: * @val: the precomputed value * @retValue: the returned value * * Get a the cononical lexical representation of the value. * The caller has to FREE the returned retValue. * * WARNING: Some value types are not supported yet, resulting * in a @retValue of "???". * * TODO: XML Schema 1.0 does not define canonical representations * for: duration, gYearMonth, gYear, gMonthDay, gMonth, gDay, * anyURI, QName, NOTATION. This will be fixed in XML Schema 1.1. * * * Returns 0 if the value could be built, 1 if the value type is * not supported yet and -1 in case of API errors. */ int xmlSchemaGetCanonValue(xmlSchemaValPtr val, const xmlChar **retValue) { if ((retValue == NULL) || (val == NULL)) return (-1); *retValue = NULL; switch (val->type) { case XML_SCHEMAS_STRING: if (val->value.str == NULL) *retValue = BAD_CAST xmlStrdup(BAD_CAST ""); else *retValue = BAD_CAST xmlStrdup((const xmlChar *) val->value.str); break; case XML_SCHEMAS_NORMSTRING: if (val->value.str == NULL) *retValue = BAD_CAST xmlStrdup(BAD_CAST ""); else { *retValue = xmlSchemaWhiteSpaceReplace( (const xmlChar *) val->value.str); if ((*retValue) == NULL) *retValue = BAD_CAST xmlStrdup( (const xmlChar *) val->value.str); } break; case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: case XML_SCHEMAS_NMTOKEN: case XML_SCHEMAS_NAME: case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_ID: case XML_SCHEMAS_IDREF: case XML_SCHEMAS_ENTITY: case XML_SCHEMAS_NOTATION: /* Unclear */ case XML_SCHEMAS_ANYURI: /* Unclear */ if (val->value.str == NULL) return (-1); *retValue = BAD_CAST xmlSchemaCollapseString(BAD_CAST val->value.str); if (*retValue == NULL) *retValue = BAD_CAST xmlStrdup((const xmlChar *) val->value.str); break; case XML_SCHEMAS_QNAME: /* TODO: Unclear in XML Schema 1.0. */ if (val->value.qname.uri == NULL) { *retValue = BAD_CAST xmlStrdup(BAD_CAST val->value.qname.name); return (0); } else { *retValue = BAD_CAST xmlStrdup(BAD_CAST "{"); *retValue = BAD_CAST xmlStrcat((xmlChar *) (*retValue), BAD_CAST val->value.qname.uri); *retValue = BAD_CAST xmlStrcat((xmlChar *) (*retValue), BAD_CAST "}"); *retValue = BAD_CAST xmlStrcat((xmlChar *) (*retValue), BAD_CAST val->value.qname.uri); } break; case XML_SCHEMAS_DECIMAL: /* * TODO: Lookout for a more simple implementation. */ if ((val->value.decimal.total == 1) && (val->value.decimal.lo == 0)) { *retValue = xmlStrdup(BAD_CAST "0.0"); } else { xmlSchemaValDecimal dec = val->value.decimal; int bufsize; char *buf = NULL, *offs; /* Add room for the decimal point as well. */ bufsize = dec.total + 2; if (dec.sign) bufsize++; /* Add room for leading/trailing zero. */ if ((dec.frac == 0) || (dec.frac == dec.total)) bufsize++; buf = xmlMalloc(bufsize); if (buf == NULL) return(-1); offs = buf; if (dec.sign) *offs++ = '-'; if (dec.frac == dec.total) { *offs++ = '0'; *offs++ = '.'; } if (dec.hi != 0) snprintf(offs, bufsize - (offs - buf), "%lu%lu%lu", dec.hi, dec.mi, dec.lo); else if (dec.mi != 0) snprintf(offs, bufsize - (offs - buf), "%lu%lu", dec.mi, dec.lo); else snprintf(offs, bufsize - (offs - buf), "%lu", dec.lo); if (dec.frac != 0) { if (dec.frac != dec.total) { int diff = dec.total - dec.frac; /* * Insert the decimal point. */ memmove(offs + diff + 1, offs + diff, dec.frac +1); offs[diff] = '.'; } else { unsigned int i = 0; /* * Insert missing zeroes behind the decimal point. */ while (*(offs + i) != 0) i++; if (i < dec.total) { memmove(offs + (dec.total - i), offs, i +1); memset(offs, '0', dec.total - i); } } } else { /* * Append decimal point and zero. */ offs = buf + bufsize - 1; *offs-- = 0; *offs-- = '0'; *offs-- = '.'; } *retValue = BAD_CAST buf; } break; case XML_SCHEMAS_INTEGER: case XML_SCHEMAS_PINTEGER: case XML_SCHEMAS_NPINTEGER: case XML_SCHEMAS_NINTEGER: case XML_SCHEMAS_NNINTEGER: case XML_SCHEMAS_LONG: case XML_SCHEMAS_BYTE: case XML_SCHEMAS_SHORT: case XML_SCHEMAS_INT: case XML_SCHEMAS_UINT: case XML_SCHEMAS_ULONG: case XML_SCHEMAS_USHORT: case XML_SCHEMAS_UBYTE: if ((val->value.decimal.total == 1) && (val->value.decimal.lo == 0)) *retValue = xmlStrdup(BAD_CAST "0"); else { xmlSchemaValDecimal dec = val->value.decimal; int bufsize = dec.total + 1; /* Add room for the decimal point as well. */ if (dec.sign) bufsize++; *retValue = xmlMalloc(bufsize); if (*retValue == NULL) return(-1); if (dec.hi != 0) { if (dec.sign) snprintf((char *) *retValue, bufsize, "-%lu%lu%lu", dec.hi, dec.mi, dec.lo); else snprintf((char *) *retValue, bufsize, "%lu%lu%lu", dec.hi, dec.mi, dec.lo); } else if (dec.mi != 0) { if (dec.sign) snprintf((char *) *retValue, bufsize, "-%lu%lu", dec.mi, dec.lo); else snprintf((char *) *retValue, bufsize, "%lu%lu", dec.mi, dec.lo); } else { if (dec.sign) snprintf((char *) *retValue, bufsize, "-%lu", dec.lo); else snprintf((char *) *retValue, bufsize, "%lu", dec.lo); } } break; case XML_SCHEMAS_BOOLEAN: if (val->value.b) *retValue = BAD_CAST xmlStrdup(BAD_CAST "true"); else *retValue = BAD_CAST xmlStrdup(BAD_CAST "false"); break; case XML_SCHEMAS_DURATION: { char buf[100]; unsigned long year; unsigned long mon, day, hour = 0, min = 0; double sec = 0, left; /* TODO: Unclear in XML Schema 1.0 */ /* * TODO: This results in a normalized output of the value * - which is NOT conformant to the spec - * since the exact values of each property are not * recoverable. Think about extending the structure to * provide a field for every property. */ year = (unsigned long) FQUOTIENT(labs(val->value.dur.mon), 12); mon = labs(val->value.dur.mon) - 12 * year; day = (unsigned long) FQUOTIENT(fabs(val->value.dur.sec), 86400); left = fabs(val->value.dur.sec) - day * 86400; if (left > 0) { hour = (unsigned long) FQUOTIENT(left, 3600); left = left - (hour * 3600); if (left > 0) { min = (unsigned long) FQUOTIENT(left, 60); sec = left - (min * 60); } } if ((val->value.dur.mon < 0) || (val->value.dur.sec < 0)) snprintf(buf, 100, "P%luY%luM%luDT%luH%luM%.14gS", year, mon, day, hour, min, sec); else snprintf(buf, 100, "-P%luY%luM%luDT%luH%luM%.14gS", year, mon, day, hour, min, sec); *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; case XML_SCHEMAS_GYEAR: { char buf[30]; /* TODO: Unclear in XML Schema 1.0 */ /* TODO: What to do with the timezone? */ snprintf(buf, 30, "%04ld", val->value.date.year); *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; case XML_SCHEMAS_GMONTH: { /* TODO: Unclear in XML Schema 1.0 */ /* TODO: What to do with the timezone? */ *retValue = xmlMalloc(6); if (*retValue == NULL) return(-1); snprintf((char *) *retValue, 6, "--%02u", val->value.date.mon); } break; case XML_SCHEMAS_GDAY: { /* TODO: Unclear in XML Schema 1.0 */ /* TODO: What to do with the timezone? */ *retValue = xmlMalloc(6); if (*retValue == NULL) return(-1); snprintf((char *) *retValue, 6, "---%02u", val->value.date.day); } break; case XML_SCHEMAS_GMONTHDAY: { /* TODO: Unclear in XML Schema 1.0 */ /* TODO: What to do with the timezone? */ *retValue = xmlMalloc(8); if (*retValue == NULL) return(-1); snprintf((char *) *retValue, 8, "--%02u-%02u", val->value.date.mon, val->value.date.day); } break; case XML_SCHEMAS_GYEARMONTH: { char buf[35]; /* TODO: Unclear in XML Schema 1.0 */ /* TODO: What to do with the timezone? */ if (val->value.date.year < 0) snprintf(buf, 35, "-%04ld-%02u", labs(val->value.date.year), val->value.date.mon); else snprintf(buf, 35, "%04ld-%02u", val->value.date.year, val->value.date.mon); *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; case XML_SCHEMAS_TIME: { char buf[30]; if (val->value.date.tz_flag) { xmlSchemaValPtr norm; norm = xmlSchemaDateNormalize(val, 0); if (norm == NULL) return (-1); /* * TODO: Check if "%.14g" is portable. */ snprintf(buf, 30, "%02u:%02u:%02.14gZ", norm->value.date.hour, norm->value.date.min, norm->value.date.sec); xmlSchemaFreeValue(norm); } else { snprintf(buf, 30, "%02u:%02u:%02.14g", val->value.date.hour, val->value.date.min, val->value.date.sec); } *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; case XML_SCHEMAS_DATE: { char buf[30]; if (val->value.date.tz_flag) { xmlSchemaValPtr norm; norm = xmlSchemaDateNormalize(val, 0); if (norm == NULL) return (-1); /* * TODO: Append the canonical value of the * recoverable timezone and not "Z". */ snprintf(buf, 30, "%04ld:%02u:%02uZ", norm->value.date.year, norm->value.date.mon, norm->value.date.day); xmlSchemaFreeValue(norm); } else { snprintf(buf, 30, "%04ld:%02u:%02u", val->value.date.year, val->value.date.mon, val->value.date.day); } *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; case XML_SCHEMAS_DATETIME: { char buf[50]; if (val->value.date.tz_flag) { xmlSchemaValPtr norm; norm = xmlSchemaDateNormalize(val, 0); if (norm == NULL) return (-1); /* * TODO: Check if "%.14g" is portable. */ snprintf(buf, 50, "%04ld:%02u:%02uT%02u:%02u:%02.14gZ", norm->value.date.year, norm->value.date.mon, norm->value.date.day, norm->value.date.hour, norm->value.date.min, norm->value.date.sec); xmlSchemaFreeValue(norm); } else { snprintf(buf, 50, "%04ld:%02u:%02uT%02u:%02u:%02.14g", val->value.date.year, val->value.date.mon, val->value.date.day, val->value.date.hour, val->value.date.min, val->value.date.sec); } *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; case XML_SCHEMAS_HEXBINARY: *retValue = BAD_CAST xmlStrdup(BAD_CAST val->value.hex.str); break; case XML_SCHEMAS_BASE64BINARY: /* * TODO: Is the following spec piece implemented?: * SPEC: "Note: For some values the canonical form defined * above does not conform to [RFC 2045], which requires breaking * with linefeeds at appropriate intervals." */ *retValue = BAD_CAST xmlStrdup(BAD_CAST val->value.base64.str); break; case XML_SCHEMAS_FLOAT: { char buf[30]; /* * |m| < 16777216, -149 <= e <= 104. * TODO: Handle, NaN, INF, -INF. The format is not * yet conformant. The c type float does not cover * the whole range. */ snprintf(buf, 30, "%01.14e", val->value.f); *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; case XML_SCHEMAS_DOUBLE: { char buf[40]; /* |m| < 9007199254740992, -1075 <= e <= 970 */ /* * TODO: Handle, NaN, INF, -INF. The format is not * yet conformant. The c type float does not cover * the whole range. */ snprintf(buf, 40, "%01.14e", val->value.d); *retValue = BAD_CAST xmlStrdup(BAD_CAST buf); } break; default: *retValue = BAD_CAST xmlStrdup(BAD_CAST "???"); return (1); } if (*retValue == NULL) return(-1); return (0); } /** * xmlSchemaGetCanonValueWhtsp: * @val: the precomputed value * @retValue: the returned value * @ws: the whitespace type of the value * * Get a the cononical representation of the value. * The caller has to free the returned @retValue. * * Returns 0 if the value could be built, 1 if the value type is * not supported yet and -1 in case of API errors. */ int xmlSchemaGetCanonValueWhtsp(xmlSchemaValPtr val, const xmlChar **retValue, xmlSchemaWhitespaceValueType ws) { if ((retValue == NULL) || (val == NULL)) return (-1); if ((ws == XML_SCHEMA_WHITESPACE_UNKNOWN) || (ws > XML_SCHEMA_WHITESPACE_COLLAPSE)) return (-1); *retValue = NULL; switch (val->type) { case XML_SCHEMAS_STRING: if (val->value.str == NULL) *retValue = BAD_CAST xmlStrdup(BAD_CAST ""); else if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) *retValue = xmlSchemaCollapseString(val->value.str); else if (ws == XML_SCHEMA_WHITESPACE_REPLACE) *retValue = xmlSchemaWhiteSpaceReplace(val->value.str); if ((*retValue) == NULL) *retValue = BAD_CAST xmlStrdup(val->value.str); break; case XML_SCHEMAS_NORMSTRING: if (val->value.str == NULL) *retValue = BAD_CAST xmlStrdup(BAD_CAST ""); else { if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) *retValue = xmlSchemaCollapseString(val->value.str); else *retValue = xmlSchemaWhiteSpaceReplace(val->value.str); if ((*retValue) == NULL) *retValue = BAD_CAST xmlStrdup(val->value.str); } break; default: return (xmlSchemaGetCanonValue(val, retValue)); } return (0); } /** * xmlSchemaGetValType: * @val: a schemas value * * Accessor for the type of a value * * Returns the xmlSchemaValType of the value */ xmlSchemaValType xmlSchemaGetValType(xmlSchemaValPtr val) { if (val == NULL) return(XML_SCHEMAS_UNKNOWN); return (val->type); } #define bottom_xmlschemastypes #include "elfgcchack.h" #endif /* LIBXML_SCHEMAS_ENABLED */ xdmf-2.1.dfsg.1/Utilities/vtklibxml2/xmllint.c0000644000175000017500000031717211606020250022434 0ustar amckinstryamckinstry/* * xmllint.c : a small tester program for XML input. * * See Copyright for the status of this software. * * daniel@veillard.com */ #include "libxml.h" #include #include #include #if defined (_WIN32) && !defined(__CYGWIN__) #if defined (_MSC_VER) || defined(__BORLANDC__) #include #pragma comment(lib, "ws2_32.lib") #define gettimeofday(p1,p2) #endif /* _MSC_VER */ #endif /* _WIN32 */ #ifdef HAVE_SYS_TIME_H #include #endif #ifdef HAVE_TIME_H #include #endif #ifdef __MINGW32__ #define _WINSOCKAPI_ #include #include #undef XML_SOCKLEN_T #define XML_SOCKLEN_T unsigned int #endif #ifdef HAVE_SYS_TIMEB_H #include #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_SYS_MMAN_H #include /* seems needed for Solaris */ #ifndef MAP_FAILED #define MAP_FAILED ((void *) -1) #endif #endif #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_LIBREADLINE #include #ifdef HAVE_LIBHISTORY #include #endif #endif #include #include #include #include #include #include #include #include #include #ifdef LIBXML_XINCLUDE_ENABLED #include #endif #ifdef LIBXML_CATALOG_ENABLED #include #endif #include #include #ifdef LIBXML_SCHEMATRON_ENABLED #include #endif #ifdef LIBXML_SCHEMAS_ENABLED #include #include #endif #ifdef LIBXML_PATTERN_ENABLED #include #endif #ifdef LIBXML_C14N_ENABLED #include #endif #ifdef LIBXML_OUTPUT_ENABLED #include #endif #ifndef XML_XML_DEFAULT_CATALOG #define XML_XML_DEFAULT_CATALOG "file:///etc/xml/catalog" #endif typedef enum { XMLLINT_RETURN_OK = 0, /* No error */ XMLLINT_ERR_UNCLASS, /* Unclassified */ XMLLINT_ERR_DTD, /* Error in DTD */ XMLLINT_ERR_VALID, /* Validation error */ XMLLINT_ERR_RDFILE, /* CtxtReadFile error */ XMLLINT_ERR_SCHEMACOMP, /* Schema compilation */ XMLLINT_ERR_OUT, /* Error writing output */ XMLLINT_ERR_SCHEMAPAT, /* Error in schema pattern */ XMLLINT_ERR_RDREGIS, /* Error in Reader registration */ XMLLINT_ERR_MEM /* Out of memory error */ } xmllintReturnCode; #ifdef LIBXML_DEBUG_ENABLED static int shell = 0; static int debugent = 0; #endif static int debug = 0; static int maxmem = 0; #ifdef LIBXML_TREE_ENABLED static int copy = 0; #endif /* LIBXML_TREE_ENABLED */ static int recovery = 0; static int noent = 0; static int noblanks = 0; static int noout = 0; static int nowrap = 0; #ifdef LIBXML_OUTPUT_ENABLED static int format = 0; static const char *output = NULL; static int compress = 0; static int oldout = 0; #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_VALID_ENABLED static int valid = 0; static int postvalid = 0; static char * dtdvalid = NULL; static char * dtdvalidfpi = NULL; #endif #ifdef LIBXML_SCHEMAS_ENABLED static char * relaxng = NULL; static xmlRelaxNGPtr relaxngschemas = NULL; static char * schema = NULL; static xmlSchemaPtr wxschemas = NULL; #endif #ifdef LIBXML_SCHEMATRON_ENABLED static char * schematron = NULL; static xmlSchematronPtr wxschematron = NULL; #endif static int repeat = 0; static int insert = 0; #if defined(LIBXML_HTML_ENABLED) || defined(LIBXML_VALID_ENABLED) static int html = 0; static int xmlout = 0; #endif static int htmlout = 0; #ifdef LIBXML_PUSH_ENABLED static int push = 0; #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H static int memory = 0; #endif static int testIO = 0; static char *encoding = NULL; #ifdef LIBXML_XINCLUDE_ENABLED static int xinclude = 0; #endif static int dtdattrs = 0; static int loaddtd = 0; static xmllintReturnCode progresult = XMLLINT_RETURN_OK; static int timing = 0; static int generate = 0; static int dropdtd = 0; #ifdef LIBXML_CATALOG_ENABLED static int catalogs = 0; static int nocatalogs = 0; #endif #ifdef LIBXML_C14N_ENABLED static int canonical = 0; static int exc_canonical = 0; #endif #ifdef LIBXML_READER_ENABLED static int stream = 0; static int walker = 0; #endif /* LIBXML_READER_ENABLED */ static int chkregister = 0; static int nbregister = 0; #ifdef LIBXML_SAX1_ENABLED static int sax1 = 0; #endif /* LIBXML_SAX1_ENABLED */ #ifdef LIBXML_PATTERN_ENABLED static const char *pattern = NULL; static xmlPatternPtr patternc = NULL; static xmlStreamCtxtPtr patstream = NULL; #endif static int options = XML_PARSE_COMPACT; static int sax = 0; /************************************************************************ * * * Entity loading control and customization. * * * ************************************************************************/ #define MAX_PATHS 64 static xmlChar *paths[MAX_PATHS + 1]; static int nbpaths = 0; static int load_trace = 0; static void parsePath(const xmlChar *path) { const xmlChar *cur; if (path == NULL) return; while (*path != 0) { if (nbpaths >= MAX_PATHS) { fprintf(stderr, "MAX_PATHS reached: too many paths\n"); return; } cur = path; while ((*cur == ' ') || (*cur == ':')) cur++; path = cur; while ((*cur != 0) && (*cur != ' ') && (*cur != ':')) cur++; if (cur != path) { paths[nbpaths] = xmlStrndup(path, cur - path); if (paths[nbpaths] != NULL) nbpaths++; path = cur; } } } static xmlExternalEntityLoader defaultEntityLoader = NULL; static xmlParserInputPtr xmllintExternalEntityLoader(const char *URL, const char *ID, xmlParserCtxtPtr ctxt) { xmlParserInputPtr ret; warningSAXFunc warning = NULL; errorSAXFunc err = NULL; int i; const char *lastsegment = URL; const char *iter = URL; if (nbpaths > 0) { while (*iter != 0) { if (*iter == '/') lastsegment = iter + 1; iter++; } } if ((ctxt != NULL) && (ctxt->sax != NULL)) { warning = ctxt->sax->warning; err = ctxt->sax->error; ctxt->sax->warning = NULL; ctxt->sax->error = NULL; } if (defaultEntityLoader != NULL) { ret = defaultEntityLoader(URL, ID, ctxt); if (ret != NULL) { if (warning != NULL) ctxt->sax->warning = warning; if (err != NULL) ctxt->sax->error = err; if (load_trace) { fprintf \ (stderr, "Loaded URL=\"%s\" ID=\"%s\"\n", URL ? URL : "(null)", ID ? ID : "(null)"); } return(ret); } } for (i = 0;i < nbpaths;i++) { xmlChar *newURL; newURL = xmlStrdup((const xmlChar *) paths[i]); newURL = xmlStrcat(newURL, (const xmlChar *) "/"); newURL = xmlStrcat(newURL, (const xmlChar *) lastsegment); if (newURL != NULL) { ret = defaultEntityLoader((const char *)newURL, ID, ctxt); if (ret != NULL) { if (warning != NULL) ctxt->sax->warning = warning; if (err != NULL) ctxt->sax->error = err; if (load_trace) { fprintf \ (stderr, "Loaded URL=\"%s\" ID=\"%s\"\n", newURL, ID ? ID : "(null)"); } xmlFree(newURL); return(ret); } xmlFree(newURL); } } if (err != NULL) ctxt->sax->error = err; if (warning != NULL) { ctxt->sax->warning = warning; if (URL != NULL) warning(ctxt, "failed to load external entity \"%s\"\n", URL); else if (ID != NULL) warning(ctxt, "failed to load external entity \"%s\"\n", ID); } return(NULL); } /************************************************************************ * * * Memory allocation consumption debugging * * * ************************************************************************/ static void OOM(void) { fprintf(stderr, "Ran out of memory needs > %d bytes\n", maxmem); progresult = XMLLINT_ERR_MEM; } static void myFreeFunc(void *mem) { xmlMemFree(mem); } static void * myMallocFunc(size_t size) { void *ret; ret = xmlMemMalloc(size); if (ret != NULL) { if (xmlMemUsed() > maxmem) { OOM(); xmlMemFree(ret); return (NULL); } } return (ret); } static void * myReallocFunc(void *mem, size_t size) { void *ret; ret = xmlMemRealloc(mem, size); if (ret != NULL) { if (xmlMemUsed() > maxmem) { OOM(); xmlMemFree(ret); return (NULL); } } return (ret); } static char * myStrdupFunc(const char *str) { char *ret; ret = xmlMemoryStrdup(str); if (ret != NULL) { if (xmlMemUsed() > maxmem) { OOM(); xmlFree(ret); return (NULL); } } return (ret); } /************************************************************************ * * * Internal timing routines to remove the necessity to have * * unix-specific function calls. * * * ************************************************************************/ #ifndef HAVE_GETTIMEOFDAY #ifdef HAVE_SYS_TIMEB_H #ifdef HAVE_SYS_TIME_H #ifdef HAVE_FTIME static int my_gettimeofday(struct timeval *tvp, void *tzp) { struct timeb timebuffer; ftime(&timebuffer); if (tvp) { tvp->tv_sec = timebuffer.time; tvp->tv_usec = timebuffer.millitm * 1000L; } return (0); } #define HAVE_GETTIMEOFDAY 1 #define gettimeofday my_gettimeofday #endif /* HAVE_FTIME */ #endif /* HAVE_SYS_TIME_H */ #endif /* HAVE_SYS_TIMEB_H */ #endif /* !HAVE_GETTIMEOFDAY */ #if defined(HAVE_GETTIMEOFDAY) static struct timeval begin, end; /* * startTimer: call where you want to start timing */ static void startTimer(void) { gettimeofday(&begin, NULL); } /* * endTimer: call where you want to stop timing and to print out a * message about the timing performed; format is a printf * type argument */ static void XMLCDECL endTimer(const char *fmt, ...) { long msec; va_list ap; gettimeofday(&end, NULL); msec = end.tv_sec - begin.tv_sec; msec *= 1000; msec += (end.tv_usec - begin.tv_usec) / 1000; #ifndef HAVE_STDARG_H #error "endTimer required stdarg functions" #endif va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, " took %ld ms\n", msec); } #elif defined(HAVE_TIME_H) /* * No gettimeofday function, so we have to make do with calling clock. * This is obviously less accurate, but there's little we can do about * that. */ #ifndef CLOCKS_PER_SEC #define CLOCKS_PER_SEC 100 #endif static clock_t begin, end; static void startTimer(void) { begin = clock(); } static void XMLCDECL endTimer(const char *fmt, ...) { long msec; va_list ap; end = clock(); msec = ((end - begin) * 1000) / CLOCKS_PER_SEC; #ifndef HAVE_STDARG_H #error "endTimer required stdarg functions" #endif va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, " took %ld ms\n", msec); } #else /* * We don't have a gettimeofday or time.h, so we just don't do timing */ static void startTimer(void) { /* * Do nothing */ } static void XMLCDECL endTimer(char *format, ...) { /* * We cannot do anything because we don't have a timing function */ #ifdef HAVE_STDARG_H va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); fprintf(stderr, " was not timed\n", msec); #else /* We don't have gettimeofday, time or stdarg.h, what crazy world is * this ?! */ #endif } #endif /************************************************************************ * * * HTML ouput * * * ************************************************************************/ static char buffer[50000]; static void xmlHTMLEncodeSend(void) { char *result; result = (char *) xmlEncodeEntitiesReentrant(NULL, BAD_CAST buffer); if (result) { xmlGenericError(xmlGenericErrorContext, "%s", result); xmlFree(result); } buffer[0] = 0; } /** * xmlHTMLPrintFileInfo: * @input: an xmlParserInputPtr input * * Displays the associated file and line informations for the current input */ static void xmlHTMLPrintFileInfo(xmlParserInputPtr input) { int len; xmlGenericError(xmlGenericErrorContext, "

"); len = strlen(buffer); if (input != NULL) { if (input->filename) { snprintf(&buffer[len], sizeof(buffer) - len, "%s:%d: ", input->filename, input->line); } else { snprintf(&buffer[len], sizeof(buffer) - len, "Entity: line %d: ", input->line); } } xmlHTMLEncodeSend(); } /** * xmlHTMLPrintFileContext: * @input: an xmlParserInputPtr input * * Displays current context within the input content for error tracking */ static void xmlHTMLPrintFileContext(xmlParserInputPtr input) { const xmlChar *cur, *base; int len; int n; if (input == NULL) return; xmlGenericError(xmlGenericErrorContext, "

\n");
    cur = input->cur;
    base = input->base;
    while ((cur > base) && ((*cur == '\n') || (*cur == '\r'))) {
        cur--;
    }
    n = 0;
    while ((n++ < 80) && (cur > base) && (*cur != '\n') && (*cur != '\r'))
        cur--;
    if ((*cur == '\n') || (*cur == '\r')) cur++;
    base = cur;
    n = 0;
    while ((*cur != 0) && (*cur != '\n') && (*cur != '\r') && (n < 79)) {
        len = strlen(buffer);
        snprintf(&buffer[len], sizeof(buffer) - len, "%c", 
                    (unsigned char) *cur++);
        n++;
    }
    len = strlen(buffer);
    snprintf(&buffer[len], sizeof(buffer) - len, "\n");
    cur = input->cur;
    while ((*cur == '\n') || (*cur == '\r'))
        cur--;
    n = 0;
    while ((cur != base) && (n++ < 80)) {
        len = strlen(buffer);
        snprintf(&buffer[len], sizeof(buffer) - len, " ");
        base++;
    }
    len = strlen(buffer);
    snprintf(&buffer[len], sizeof(buffer) - len, "^\n");
    xmlHTMLEncodeSend();
    xmlGenericError(xmlGenericErrorContext, "
"); } /** * xmlHTMLError: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format an error messages, gives file, line, position and * extra parameters. */ static void XMLCDECL xmlHTMLError(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input != NULL) && (input->filename == NULL) && (ctxt->inputNr > 1)) { input = ctxt->inputTab[ctxt->inputNr - 2]; } xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "error: "); va_start(args, msg); len = strlen(buffer); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "

\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); } /** * xmlHTMLWarning: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a warning messages, gives file, line, position and * extra parameters. */ static void XMLCDECL xmlHTMLWarning(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input != NULL) && (input->filename == NULL) && (ctxt->inputNr > 1)) { input = ctxt->inputTab[ctxt->inputNr - 2]; } xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "warning: "); va_start(args, msg); len = strlen(buffer); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "

\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); } /** * xmlHTMLValidityError: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format an validity error messages, gives file, * line, position and extra parameters. */ static void XMLCDECL xmlHTMLValidityError(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input->filename == NULL) && (ctxt->inputNr > 1)) input = ctxt->inputTab[ctxt->inputNr - 2]; xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "validity error: "); len = strlen(buffer); va_start(args, msg); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "

\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); progresult = XMLLINT_ERR_VALID; } /** * xmlHTMLValidityWarning: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a validity warning messages, gives file, line, * position and extra parameters. */ static void XMLCDECL xmlHTMLValidityWarning(void *ctx, const char *msg, ...) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; xmlParserInputPtr input; va_list args; int len; buffer[0] = 0; input = ctxt->input; if ((input->filename == NULL) && (ctxt->inputNr > 1)) input = ctxt->inputTab[ctxt->inputNr - 2]; xmlHTMLPrintFileInfo(input); xmlGenericError(xmlGenericErrorContext, "validity warning: "); va_start(args, msg); len = strlen(buffer); vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args); va_end(args); xmlHTMLEncodeSend(); xmlGenericError(xmlGenericErrorContext, "

\n"); xmlHTMLPrintFileContext(input); xmlHTMLEncodeSend(); } /************************************************************************ * * * Shell Interface * * * ************************************************************************/ #ifdef LIBXML_DEBUG_ENABLED #ifdef LIBXML_XPATH_ENABLED /** * xmlShellReadline: * @prompt: the prompt value * * Read a string * * Returns a pointer to it or NULL on EOF the caller is expected to * free the returned string. */ static char * xmlShellReadline(char *prompt) { #ifdef HAVE_LIBREADLINE char *line_read; /* Get a line from the user. */ line_read = readline (prompt); /* If the line has any text in it, save it on the history. */ if (line_read && *line_read) add_history (line_read); return (line_read); #else char line_read[501]; char *ret; int len; if (prompt != NULL) fprintf(stdout, "%s", prompt); if (!fgets(line_read, 500, stdin)) return(NULL); line_read[500] = 0; len = strlen(line_read); ret = (char *) malloc(len + 1); if (ret != NULL) { memcpy (ret, line_read, len + 1); } return(ret); #endif } #endif /* LIBXML_XPATH_ENABLED */ #endif /* LIBXML_DEBUG_ENABLED */ /************************************************************************ * * * I/O Interfaces * * * ************************************************************************/ static int myRead(FILE *f, char * buf, int len) { return(fread(buf, 1, len, f)); } static void myClose(FILE *f) { if (f != stdin) { fclose(f); } } /************************************************************************ * * * SAX based tests * * * ************************************************************************/ /* * empty SAX block */ static xmlSAXHandler emptySAXHandlerStruct = { NULL, /* internalSubset */ NULL, /* isStandalone */ NULL, /* hasInternalSubset */ NULL, /* hasExternalSubset */ NULL, /* resolveEntity */ NULL, /* getEntity */ NULL, /* entityDecl */ NULL, /* notationDecl */ NULL, /* attributeDecl */ NULL, /* elementDecl */ NULL, /* unparsedEntityDecl */ NULL, /* setDocumentLocator */ NULL, /* startDocument */ NULL, /* endDocument */ NULL, /* startElement */ NULL, /* endElement */ NULL, /* reference */ NULL, /* characters */ NULL, /* ignorableWhitespace */ NULL, /* processingInstruction */ NULL, /* comment */ NULL, /* xmlParserWarning */ NULL, /* xmlParserError */ NULL, /* xmlParserError */ NULL, /* getParameterEntity */ NULL, /* cdataBlock; */ NULL, /* externalSubset; */ XML_SAX2_MAGIC, NULL, NULL, /* startElementNs */ NULL, /* endElementNs */ NULL /* xmlStructuredErrorFunc */ }; static xmlSAXHandlerPtr emptySAXHandler = &emptySAXHandlerStruct; extern xmlSAXHandlerPtr debugSAXHandler; static int callbacks; /** * isStandaloneDebug: * @ctxt: An XML parser context * * Is this document tagged standalone ? * * Returns 1 if true */ static int isStandaloneDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return(0); fprintf(stdout, "SAX.isStandalone()\n"); return(0); } /** * hasInternalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an internal subset * * Returns 1 if true */ static int hasInternalSubsetDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return(0); fprintf(stdout, "SAX.hasInternalSubset()\n"); return(0); } /** * hasExternalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an external subset * * Returns 1 if true */ static int hasExternalSubsetDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return(0); fprintf(stdout, "SAX.hasExternalSubset()\n"); return(0); } /** * internalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an internal subset */ static void internalSubsetDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { callbacks++; if (noout) return; fprintf(stdout, "SAX.internalSubset(%s,", name); if (ExternalID == NULL) fprintf(stdout, " ,"); else fprintf(stdout, " %s,", ExternalID); if (SystemID == NULL) fprintf(stdout, " )\n"); else fprintf(stdout, " %s)\n", SystemID); } /** * externalSubsetDebug: * @ctxt: An XML parser context * * Does this document has an external subset */ static void externalSubsetDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { callbacks++; if (noout) return; fprintf(stdout, "SAX.externalSubset(%s,", name); if (ExternalID == NULL) fprintf(stdout, " ,"); else fprintf(stdout, " %s,", ExternalID); if (SystemID == NULL) fprintf(stdout, " )\n"); else fprintf(stdout, " %s)\n", SystemID); } /** * resolveEntityDebug: * @ctxt: An XML parser context * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * Special entity resolver, better left to the parser, it has * more context than the application layer. * The default behaviour is to NOT resolve the entities, in that case * the ENTITY_REF nodes are built in the structure (and the parameter * values). * * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour. */ static xmlParserInputPtr resolveEntityDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *publicId, const xmlChar *systemId) { callbacks++; if (noout) return(NULL); /* xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; */ fprintf(stdout, "SAX.resolveEntity("); if (publicId != NULL) fprintf(stdout, "%s", (char *)publicId); else fprintf(stdout, " "); if (systemId != NULL) fprintf(stdout, ", %s)\n", (char *)systemId); else fprintf(stdout, ", )\n"); return(NULL); } /** * getEntityDebug: * @ctxt: An XML parser context * @name: The entity name * * Get an entity by name * * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour. */ static xmlEntityPtr getEntityDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (noout) return(NULL); fprintf(stdout, "SAX.getEntity(%s)\n", name); return(NULL); } /** * getParameterEntityDebug: * @ctxt: An XML parser context * @name: The entity name * * Get a parameter entity by name * * Returns the xmlParserInputPtr */ static xmlEntityPtr getParameterEntityDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (noout) return(NULL); fprintf(stdout, "SAX.getParameterEntity(%s)\n", name); return(NULL); } /** * entityDeclDebug: * @ctxt: An XML parser context * @name: the entity name * @type: the entity type * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @content: the entity value (without processing). * * An entity definition has been parsed */ static void entityDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content) { const xmlChar *nullstr = BAD_CAST "(null)"; /* not all libraries handle printing null pointers nicely */ if (publicId == NULL) publicId = nullstr; if (systemId == NULL) systemId = nullstr; if (content == NULL) content = (xmlChar *)nullstr; callbacks++; if (noout) return; fprintf(stdout, "SAX.entityDecl(%s, %d, %s, %s, %s)\n", name, type, publicId, systemId, content); } /** * attributeDeclDebug: * @ctxt: An XML parser context * @name: the attribute name * @type: the attribute type * * An attribute definition has been parsed */ static void attributeDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar * elem, const xmlChar * name, int type, int def, const xmlChar * defaultValue, xmlEnumerationPtr tree) { callbacks++; if (noout) return; if (defaultValue == NULL) fprintf(stdout, "SAX.attributeDecl(%s, %s, %d, %d, NULL, ...)\n", elem, name, type, def); else fprintf(stdout, "SAX.attributeDecl(%s, %s, %d, %d, %s, ...)\n", elem, name, type, def, defaultValue); xmlFreeEnumeration(tree); } /** * elementDeclDebug: * @ctxt: An XML parser context * @name: the element name * @type: the element type * @content: the element value (without processing). * * An element definition has been parsed */ static void elementDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, int type, xmlElementContentPtr content ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.elementDecl(%s, %d, ...)\n", name, type); } /** * notationDeclDebug: * @ctxt: An XML parser context * @name: The name of the notation * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * What to do when a notation declaration has been parsed. */ static void notationDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId) { callbacks++; if (noout) return; fprintf(stdout, "SAX.notationDecl(%s, %s, %s)\n", (char *) name, (char *) publicId, (char *) systemId); } /** * unparsedEntityDeclDebug: * @ctxt: An XML parser context * @name: The name of the entity * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @notationName: the name of the notation * * What to do when an unparsed entity declaration is parsed */ static void unparsedEntityDeclDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName) { const xmlChar *nullstr = BAD_CAST "(null)"; if (publicId == NULL) publicId = nullstr; if (systemId == NULL) systemId = nullstr; if (notationName == NULL) notationName = nullstr; callbacks++; if (noout) return; fprintf(stdout, "SAX.unparsedEntityDecl(%s, %s, %s, %s)\n", (char *) name, (char *) publicId, (char *) systemId, (char *) notationName); } /** * setDocumentLocatorDebug: * @ctxt: An XML parser context * @loc: A SAX Locator * * Receive the document locator at startup, actually xmlDefaultSAXLocator * Everything is available on the context, so this is useless in our case. */ static void setDocumentLocatorDebug(void *ctx ATTRIBUTE_UNUSED, xmlSAXLocatorPtr loc ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.setDocumentLocator()\n"); } /** * startDocumentDebug: * @ctxt: An XML parser context * * called when the document start being processed. */ static void startDocumentDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.startDocument()\n"); } /** * endDocumentDebug: * @ctxt: An XML parser context * * called when the document end has been detected. */ static void endDocumentDebug(void *ctx ATTRIBUTE_UNUSED) { callbacks++; if (noout) return; fprintf(stdout, "SAX.endDocument()\n"); } /** * startElementDebug: * @ctxt: An XML parser context * @name: The element name * * called when an opening tag has been processed. */ static void startElementDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar **atts) { int i; callbacks++; if (noout) return; fprintf(stdout, "SAX.startElement(%s", (char *) name); if (atts != NULL) { for (i = 0;(atts[i] != NULL);i++) { fprintf(stdout, ", %s='", atts[i++]); if (atts[i] != NULL) fprintf(stdout, "%s'", atts[i]); } } fprintf(stdout, ")\n"); } /** * endElementDebug: * @ctxt: An XML parser context * @name: The element name * * called when the end of an element has been detected. */ static void endElementDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (noout) return; fprintf(stdout, "SAX.endElement(%s)\n", (char *) name); } /** * charactersDebug: * @ctxt: An XML parser context * @ch: a xmlChar string * @len: the number of xmlChar * * receiving some chars from the parser. * Question: how much at a time ??? */ static void charactersDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *ch, int len) { char out[40]; int i; callbacks++; if (noout) return; for (i = 0;(i 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } } xmlSchemaFreeValidCtxt(vctxt); } else #endif { /* * Create the parser context amd hook the input */ ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { xmlFreeParserInputBuffer(buf); goto error; } old_sax = ctxt->sax; ctxt->sax = handler; ctxt->userData = (void *) user_data; inputStream = xmlNewIOInputStream(ctxt, buf, XML_CHAR_ENCODING_NONE); if (inputStream == NULL) { xmlFreeParserInputBuffer(buf); goto error; } inputPush(ctxt, inputStream); /* do the parsing */ xmlParseDocument(ctxt); if (ctxt->myDoc != NULL) { fprintf(stderr, "SAX generated a doc !\n"); xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } } error: if (ctxt != NULL) { ctxt->sax = old_sax; xmlFreeParserCtxt(ctxt); } } /************************************************************************ * * * Stream Test processing * * * ************************************************************************/ #ifdef LIBXML_READER_ENABLED static void processNode(xmlTextReaderPtr reader) { const xmlChar *name, *value; int type, empty; type = xmlTextReaderNodeType(reader); empty = xmlTextReaderIsEmptyElement(reader); if (debug) { name = xmlTextReaderConstName(reader); if (name == NULL) name = BAD_CAST "--"; value = xmlTextReaderConstValue(reader); printf("%d %d %s %d %d", xmlTextReaderDepth(reader), type, name, empty, xmlTextReaderHasValue(reader)); if (value == NULL) printf("\n"); else { printf(" %s\n", value); } } #ifdef LIBXML_PATTERN_ENABLED if (patternc) { xmlChar *path = NULL; int match = -1; if (type == XML_READER_TYPE_ELEMENT) { /* do the check only on element start */ match = xmlPatternMatch(patternc, xmlTextReaderCurrentNode(reader)); if (match) { path = xmlGetNodePath(xmlTextReaderCurrentNode(reader)); printf("Node %s matches pattern %s\n", path, pattern); } } if (patstream != NULL) { int ret; if (type == XML_READER_TYPE_ELEMENT) { ret = xmlStreamPush(patstream, xmlTextReaderConstLocalName(reader), xmlTextReaderConstNamespaceUri(reader)); if (ret < 0) { fprintf(stderr, "xmlStreamPush() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } else if (ret != match) { if (path == NULL) { path = xmlGetNodePath( xmlTextReaderCurrentNode(reader)); } fprintf(stderr, "xmlPatternMatch and xmlStreamPush disagree\n"); fprintf(stderr, " pattern %s node %s\n", pattern, path); } } if ((type == XML_READER_TYPE_END_ELEMENT) || ((type == XML_READER_TYPE_ELEMENT) && (empty))) { ret = xmlStreamPop(patstream); if (ret < 0) { fprintf(stderr, "xmlStreamPop() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } } } if (path != NULL) xmlFree(path); } #endif } static void streamFile(char *filename) { xmlTextReaderPtr reader; int ret; #ifdef HAVE_SYS_MMAN_H int fd = -1; struct stat info; const char *base = NULL; xmlParserInputBufferPtr input = NULL; if (memory) { if (stat(filename, &info) < 0) return; if ((fd = open(filename, O_RDONLY)) < 0) return; base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (base == (void *) MAP_FAILED) return; reader = xmlReaderForMemory(base, info.st_size, filename, NULL, options); } else #endif reader = xmlReaderForFile(filename, NULL, options); #ifdef LIBXML_PATTERN_ENABLED if (pattern != NULL) { patternc = xmlPatterncompile((const xmlChar *) pattern, NULL, 0, NULL); if (patternc == NULL) { xmlGenericError(xmlGenericErrorContext, "Pattern %s failed to compile\n", pattern); progresult = XMLLINT_ERR_SCHEMAPAT; pattern = NULL; } } if (patternc != NULL) { patstream = xmlPatternGetStreamCtxt(patternc); if (patstream != NULL) { ret = xmlStreamPush(patstream, NULL, NULL); if (ret < 0) { fprintf(stderr, "xmlStreamPush() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } } } #endif if (reader != NULL) { #ifdef LIBXML_VALID_ENABLED if (valid) xmlTextReaderSetParserProp(reader, XML_PARSER_VALIDATE, 1); else #endif /* LIBXML_VALID_ENABLED */ xmlTextReaderSetParserProp(reader, XML_PARSER_LOADDTD, 1); #ifdef LIBXML_SCHEMAS_ENABLED if (relaxng != NULL) { if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderRelaxNGValidate(reader, relaxng); if (ret < 0) { xmlGenericError(xmlGenericErrorContext, "Relax-NG schema %s failed to compile\n", relaxng); progresult = XMLLINT_ERR_SCHEMACOMP; relaxng = NULL; } if ((timing) && (!repeat)) { endTimer("Compiling the schemas"); } } if (schema != NULL) { if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderSchemaValidate(reader, schema); if (ret < 0) { xmlGenericError(xmlGenericErrorContext, "XSD schema %s failed to compile\n", schema); progresult = XMLLINT_ERR_SCHEMACOMP; schema = NULL; } if ((timing) && (!repeat)) { endTimer("Compiling the schemas"); } } #endif /* * Process all nodes in sequence */ if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderRead(reader); while (ret == 1) { if ((debug) #ifdef LIBXML_PATTERN_ENABLED || (patternc) #endif ) processNode(reader); ret = xmlTextReaderRead(reader); } if ((timing) && (!repeat)) { #ifdef LIBXML_SCHEMAS_ENABLED if (relaxng != NULL) endTimer("Parsing and validating"); else #endif #ifdef LIBXML_VALID_ENABLED if (valid) endTimer("Parsing and validating"); else #endif endTimer("Parsing"); } #ifdef LIBXML_VALID_ENABLED if (valid) { if (xmlTextReaderIsValid(reader) != 1) { xmlGenericError(xmlGenericErrorContext, "Document %s does not validate\n", filename); progresult = XMLLINT_ERR_VALID; } } #endif /* LIBXML_VALID_ENABLED */ #ifdef LIBXML_SCHEMAS_ENABLED if ((relaxng != NULL) || (schema != NULL)) { if (xmlTextReaderIsValid(reader) != 1) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validates\n", filename); } } #endif /* * Done, cleanup and status */ xmlFreeTextReader(reader); if (ret != 0) { fprintf(stderr, "%s : failed to parse\n", filename); progresult = XMLLINT_ERR_UNCLASS; } } else { fprintf(stderr, "Unable to open %s\n", filename); progresult = XMLLINT_ERR_UNCLASS; } #ifdef LIBXML_PATTERN_ENABLED if (patstream != NULL) { xmlFreeStreamCtxt(patstream); patstream = NULL; } #endif #ifdef HAVE_SYS_MMAN_H if (memory) { xmlFreeParserInputBuffer(input); munmap((char *) base, info.st_size); close(fd); } #endif } static void walkDoc(xmlDocPtr doc) { xmlTextReaderPtr reader; int ret; #ifdef LIBXML_PATTERN_ENABLED xmlNodePtr root; const xmlChar *namespaces[22]; int i; xmlNsPtr ns; root = xmlDocGetRootElement(doc); for (ns = root->nsDef, i = 0;ns != NULL && i < 20;ns=ns->next) { namespaces[i++] = ns->href; namespaces[i++] = ns->prefix; } namespaces[i++] = NULL; namespaces[i++] = NULL; if (pattern != NULL) { patternc = xmlPatterncompile((const xmlChar *) pattern, doc->dict, 0, &namespaces[0]); if (patternc == NULL) { xmlGenericError(xmlGenericErrorContext, "Pattern %s failed to compile\n", pattern); progresult = XMLLINT_ERR_SCHEMAPAT; pattern = NULL; } } if (patternc != NULL) { patstream = xmlPatternGetStreamCtxt(patternc); if (patstream != NULL) { ret = xmlStreamPush(patstream, NULL, NULL); if (ret < 0) { fprintf(stderr, "xmlStreamPush() failure\n"); xmlFreeStreamCtxt(patstream); patstream = NULL; } } } #endif /* LIBXML_PATTERN_ENABLED */ reader = xmlReaderWalker(doc); if (reader != NULL) { if ((timing) && (!repeat)) { startTimer(); } ret = xmlTextReaderRead(reader); while (ret == 1) { if ((debug) #ifdef LIBXML_PATTERN_ENABLED || (patternc) #endif ) processNode(reader); ret = xmlTextReaderRead(reader); } if ((timing) && (!repeat)) { endTimer("walking through the doc"); } xmlFreeTextReader(reader); if (ret != 0) { fprintf(stderr, "failed to walk through the doc\n"); progresult = XMLLINT_ERR_UNCLASS; } } else { fprintf(stderr, "Failed to crate a reader from the document\n"); progresult = XMLLINT_ERR_UNCLASS; } #ifdef LIBXML_PATTERN_ENABLED if (patstream != NULL) { xmlFreeStreamCtxt(patstream); patstream = NULL; } #endif } #endif /* LIBXML_READER_ENABLED */ /************************************************************************ * * * Tree Test processing * * * ************************************************************************/ static void parseAndPrintFile(char *filename, xmlParserCtxtPtr rectxt) { xmlDocPtr doc = NULL; #ifdef LIBXML_TREE_ENABLED xmlDocPtr tmp; #endif /* LIBXML_TREE_ENABLED */ if ((timing) && (!repeat)) startTimer(); #ifdef LIBXML_TREE_ENABLED if (filename == NULL) { if (generate) { xmlNodePtr n; doc = xmlNewDoc(BAD_CAST "1.0"); n = xmlNewDocNode(doc, NULL, BAD_CAST "info", NULL); xmlNodeSetContent(n, BAD_CAST "abc"); xmlDocSetRootElement(doc, n); } } #endif /* LIBXML_TREE_ENABLED */ #ifdef LIBXML_HTML_ENABLED #ifdef LIBXML_PUSH_ENABLED else if ((html) && (push)) { FILE *f; #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) f = fopen(filename, "rb"); #else f = fopen(filename, "r"); #endif if (f != NULL) { int res, size = 3; char chars[4096]; htmlParserCtxtPtr ctxt; /* if (repeat) */ size = 4096; res = fread(chars, 1, 4, f); if (res > 0) { ctxt = htmlCreatePushParserCtxt(NULL, NULL, chars, res, filename, XML_CHAR_ENCODING_NONE); while ((res = fread(chars, 1, size, f)) > 0) { htmlParseChunk(ctxt, chars, res, 0); } htmlParseChunk(ctxt, chars, 0, 1); doc = ctxt->myDoc; htmlFreeParserCtxt(ctxt); } fclose(f); } } #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H else if ((html) && (memory)) { int fd; struct stat info; const char *base; if (stat(filename, &info) < 0) return; if ((fd = open(filename, O_RDONLY)) < 0) return; base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (base == (void *) MAP_FAILED) return; doc = htmlReadMemory((char *) base, info.st_size, filename, NULL, options); munmap((char *) base, info.st_size); close(fd); } #endif else if (html) { doc = htmlReadFile(filename, NULL, options); } #endif /* LIBXML_HTML_ENABLED */ else { #ifdef LIBXML_PUSH_ENABLED /* * build an XML tree from a string; */ if (push) { FILE *f; /* '-' Usually means stdin - */ if ((filename[0] == '-') && (filename[1] == 0)) { f = stdin; } else { #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) f = fopen(filename, "rb"); #else f = fopen(filename, "r"); #endif } if (f != NULL) { int ret; int res, size = 1024; char chars[1024]; xmlParserCtxtPtr ctxt; /* if (repeat) size = 1024; */ res = fread(chars, 1, 4, f); if (res > 0) { ctxt = xmlCreatePushParserCtxt(NULL, NULL, chars, res, filename); xmlCtxtUseOptions(ctxt, options); while ((res = fread(chars, 1, size, f)) > 0) { xmlParseChunk(ctxt, chars, res, 0); } xmlParseChunk(ctxt, chars, 0, 1); doc = ctxt->myDoc; ret = ctxt->wellFormed; xmlFreeParserCtxt(ctxt); if (!ret) { xmlFreeDoc(doc); doc = NULL; } } } } else #endif /* LIBXML_PUSH_ENABLED */ if (testIO) { if ((filename[0] == '-') && (filename[1] == 0)) { doc = xmlReadFd(0, NULL, NULL, options); } else { FILE *f; #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__) f = fopen(filename, "rb"); #else f = fopen(filename, "r"); #endif if (f != NULL) { if (rectxt == NULL) doc = xmlReadIO((xmlInputReadCallback) myRead, (xmlInputCloseCallback) myClose, f, filename, NULL, options); else doc = xmlCtxtReadIO(rectxt, (xmlInputReadCallback) myRead, (xmlInputCloseCallback) myClose, f, filename, NULL, options); } else doc = NULL; } } else if (htmlout) { xmlParserCtxtPtr ctxt; if (rectxt == NULL) ctxt = xmlNewParserCtxt(); else ctxt = rectxt; if (ctxt == NULL) { doc = NULL; } else { ctxt->sax->error = xmlHTMLError; ctxt->sax->warning = xmlHTMLWarning; ctxt->vctxt.error = xmlHTMLValidityError; ctxt->vctxt.warning = xmlHTMLValidityWarning; doc = xmlCtxtReadFile(ctxt, filename, NULL, options); if (rectxt == NULL) xmlFreeParserCtxt(ctxt); } #ifdef HAVE_SYS_MMAN_H } else if (memory) { int fd; struct stat info; const char *base; if (stat(filename, &info) < 0) return; if ((fd = open(filename, O_RDONLY)) < 0) return; base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (base == (void *) MAP_FAILED) return; if (rectxt == NULL) doc = xmlReadMemory((char *) base, info.st_size, filename, NULL, options); else doc = xmlCtxtReadMemory(rectxt, (char *) base, info.st_size, filename, NULL, options); munmap((char *) base, info.st_size); close(fd); #endif #ifdef LIBXML_VALID_ENABLED } else if (valid) { xmlParserCtxtPtr ctxt = NULL; if (rectxt == NULL) ctxt = xmlNewParserCtxt(); else ctxt = rectxt; if (ctxt == NULL) { doc = NULL; } else { doc = xmlCtxtReadFile(ctxt, filename, NULL, options); if (ctxt->valid == 0) progresult = XMLLINT_ERR_RDFILE; if (rectxt == NULL) xmlFreeParserCtxt(ctxt); } #endif /* LIBXML_VALID_ENABLED */ } else { if (rectxt != NULL) doc = xmlCtxtReadFile(rectxt, filename, NULL, options); else { #ifdef LIBXML_SAX1_ENABLED if (sax1) doc = xmlParseFile(filename); else #endif /* LIBXML_SAX1_ENABLED */ doc = xmlReadFile(filename, NULL, options); } } } /* * If we don't have a document we might as well give up. Do we * want an error message here? */ if (doc == NULL) { progresult = XMLLINT_ERR_UNCLASS; return; } if ((timing) && (!repeat)) { endTimer("Parsing"); } /* * Remove DOCTYPE nodes */ if (dropdtd) { xmlDtdPtr dtd; dtd = xmlGetIntSubset(doc); if (dtd != NULL) { xmlUnlinkNode((xmlNodePtr)dtd); xmlFreeDtd(dtd); } } #ifdef LIBXML_XINCLUDE_ENABLED if (xinclude) { if ((timing) && (!repeat)) { startTimer(); } if (xmlXIncludeProcessFlags(doc, options) < 0) progresult = XMLLINT_ERR_UNCLASS; if ((timing) && (!repeat)) { endTimer("Xinclude processing"); } } #endif #ifdef LIBXML_DEBUG_ENABLED #ifdef LIBXML_XPATH_ENABLED /* * shell interaction */ if (shell) { xmlXPathOrderDocElems(doc); xmlShell(doc, filename, xmlShellReadline, stdout); } #endif #endif #ifdef LIBXML_TREE_ENABLED /* * test intermediate copy if needed. */ if (copy) { tmp = doc; if (timing) { startTimer(); } doc = xmlCopyDoc(doc, 1); if (timing) { endTimer("Copying"); } if (timing) { startTimer(); } xmlFreeDoc(tmp); if (timing) { endTimer("Freeing original"); } } #endif /* LIBXML_TREE_ENABLED */ #ifdef LIBXML_VALID_ENABLED if ((insert) && (!html)) { const xmlChar* list[256]; int nb, i; xmlNodePtr node; if (doc->children != NULL) { node = doc->children; while ((node != NULL) && (node->last == NULL)) node = node->next; if (node != NULL) { nb = xmlValidGetValidElements(node->last, NULL, list, 256); if (nb < 0) { fprintf(stderr, "could not get valid list of elements\n"); } else if (nb == 0) { fprintf(stderr, "No element can be inserted under root\n"); } else { fprintf(stderr, "%d element types can be inserted under root:\n", nb); for (i = 0;i < nb;i++) { fprintf(stderr, "%s\n", (char *) list[i]); } } } } }else #endif /* LIBXML_VALID_ENABLED */ #ifdef LIBXML_READER_ENABLED if (walker) { walkDoc(doc); } #endif /* LIBXML_READER_ENABLED */ #ifdef LIBXML_OUTPUT_ENABLED if (noout == 0) { int ret; /* * print it. */ #ifdef LIBXML_DEBUG_ENABLED if (!debug) { #endif if ((timing) && (!repeat)) { startTimer(); } #ifdef LIBXML_HTML_ENABLED if ((html) && (!xmlout)) { if (compress) { htmlSaveFile(output ? output : "-", doc); } else if (encoding != NULL) { if ( format ) { htmlSaveFileFormat(output ? output : "-", doc, encoding, 1); } else { htmlSaveFileFormat(output ? output : "-", doc, encoding, 0); } } else if (format) { htmlSaveFileFormat(output ? output : "-", doc, NULL, 1); } else { FILE *out; if (output == NULL) out = stdout; else { out = fopen(output,"wb"); } if (out != NULL) { if (htmlDocDump(out, doc) < 0) progresult = XMLLINT_ERR_OUT; if (output != NULL) fclose(out); } else { fprintf(stderr, "failed to open %s\n", output); progresult = XMLLINT_ERR_OUT; } } if ((timing) && (!repeat)) { endTimer("Saving"); } } else #endif #ifdef LIBXML_C14N_ENABLED if (canonical) { xmlChar *result = NULL; int size; size = xmlC14NDocDumpMemory(doc, NULL, 0, NULL, 1, &result); if (size >= 0) { write(1, result, size); xmlFree(result); } else { fprintf(stderr, "Failed to canonicalize\n"); progresult = XMLLINT_ERR_OUT; } } else if (exc_canonical) { xmlChar *result = NULL; int size; size = xmlC14NDocDumpMemory(doc, NULL, 1, NULL, 1, &result); if (size >= 0) { write(1, result, size); xmlFree(result); } else { fprintf(stderr, "Failed to canonicalize\n"); progresult = XMLLINT_ERR_OUT; } } else #endif #ifdef HAVE_SYS_MMAN_H if (memory) { xmlChar *result; int len; if (encoding != NULL) { if ( format ) { xmlDocDumpFormatMemoryEnc(doc, &result, &len, encoding, 1); } else { xmlDocDumpMemoryEnc(doc, &result, &len, encoding); } } else { if (format) xmlDocDumpFormatMemory(doc, &result, &len, 1); else xmlDocDumpMemory(doc, &result, &len); } if (result == NULL) { fprintf(stderr, "Failed to save\n"); progresult = XMLLINT_ERR_OUT; } else { write(1, result, len); xmlFree(result); } } else #endif /* HAVE_SYS_MMAN_H */ if (compress) { xmlSaveFile(output ? output : "-", doc); } else if (oldout) { if (encoding != NULL) { if ( format ) { ret = xmlSaveFormatFileEnc(output ? output : "-", doc, encoding, 1); } else { ret = xmlSaveFileEnc(output ? output : "-", doc, encoding); } if (ret < 0) { fprintf(stderr, "failed save to %s\n", output ? output : "-"); progresult = XMLLINT_ERR_OUT; } } else if (format) { ret = xmlSaveFormatFile(output ? output : "-", doc, 1); if (ret < 0) { fprintf(stderr, "failed save to %s\n", output ? output : "-"); progresult = XMLLINT_ERR_OUT; } } else { FILE *out; if (output == NULL) out = stdout; else { out = fopen(output,"wb"); } if (out != NULL) { if (xmlDocDump(out, doc) < 0) progresult = XMLLINT_ERR_OUT; if (output != NULL) fclose(out); } else { fprintf(stderr, "failed to open %s\n", output); progresult = XMLLINT_ERR_OUT; } } } else { xmlSaveCtxtPtr ctxt; int saveOpts = 0; if (format) saveOpts |= XML_SAVE_FORMAT; if (output == NULL) ctxt = xmlSaveToFd(1, encoding, saveOpts); else ctxt = xmlSaveToFilename(output, encoding, saveOpts); if (ctxt != NULL) { if (xmlSaveDoc(ctxt, doc) < 0) { fprintf(stderr, "failed save to %s\n", output ? output : "-"); progresult = XMLLINT_ERR_OUT; } xmlSaveClose(ctxt); } else { progresult = XMLLINT_ERR_OUT; } } if ((timing) && (!repeat)) { endTimer("Saving"); } #ifdef LIBXML_DEBUG_ENABLED } else { FILE *out; if (output == NULL) out = stdout; else { out = fopen(output,"wb"); } if (out != NULL) { xmlDebugDumpDocument(out, doc); if (output != NULL) fclose(out); } else { fprintf(stderr, "failed to open %s\n", output); progresult = XMLLINT_ERR_OUT; } } #endif } #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_VALID_ENABLED /* * A posteriori validation test */ if ((dtdvalid != NULL) || (dtdvalidfpi != NULL)) { xmlDtdPtr dtd; if ((timing) && (!repeat)) { startTimer(); } if (dtdvalid != NULL) dtd = xmlParseDTD(NULL, (const xmlChar *)dtdvalid); else dtd = xmlParseDTD((const xmlChar *)dtdvalidfpi, NULL); if ((timing) && (!repeat)) { endTimer("Parsing DTD"); } if (dtd == NULL) { if (dtdvalid != NULL) xmlGenericError(xmlGenericErrorContext, "Could not parse DTD %s\n", dtdvalid); else xmlGenericError(xmlGenericErrorContext, "Could not parse DTD %s\n", dtdvalidfpi); progresult = XMLLINT_ERR_DTD; } else { xmlValidCtxtPtr cvp; if ((cvp = xmlNewValidCtxt()) == NULL) { xmlGenericError(xmlGenericErrorContext, "Couldn't allocate validation context\n"); exit(-1); } cvp->userData = (void *) stderr; cvp->error = (xmlValidityErrorFunc) fprintf; cvp->warning = (xmlValidityWarningFunc) fprintf; if ((timing) && (!repeat)) { startTimer(); } if (!xmlValidateDtd(cvp, doc, dtd)) { if (dtdvalid != NULL) xmlGenericError(xmlGenericErrorContext, "Document %s does not validate against %s\n", filename, dtdvalid); else xmlGenericError(xmlGenericErrorContext, "Document %s does not validate against %s\n", filename, dtdvalidfpi); progresult = XMLLINT_ERR_VALID; } if ((timing) && (!repeat)) { endTimer("Validating against DTD"); } xmlFreeValidCtxt(cvp); xmlFreeDtd(dtd); } } else if (postvalid) { xmlValidCtxtPtr cvp; if ((cvp = xmlNewValidCtxt()) == NULL) { xmlGenericError(xmlGenericErrorContext, "Couldn't allocate validation context\n"); exit(-1); } if ((timing) && (!repeat)) { startTimer(); } cvp->userData = (void *) stderr; cvp->error = (xmlValidityErrorFunc) fprintf; cvp->warning = (xmlValidityWarningFunc) fprintf; if (!xmlValidateDocument(cvp, doc)) { xmlGenericError(xmlGenericErrorContext, "Document %s does not validate\n", filename); progresult = XMLLINT_ERR_VALID; } if ((timing) && (!repeat)) { endTimer("Validating"); } xmlFreeValidCtxt(cvp); } #endif /* LIBXML_VALID_ENABLED */ #ifdef LIBXML_SCHEMATRON_ENABLED if (wxschematron != NULL) { xmlSchematronValidCtxtPtr ctxt; int ret; int flag; if ((timing) && (!repeat)) { startTimer(); } if (debug) flag = XML_SCHEMATRON_OUT_XML; else flag = XML_SCHEMATRON_OUT_TEXT; if (noout) flag |= XML_SCHEMATRON_OUT_QUIET; ctxt = xmlSchematronNewValidCtxt(wxschematron, flag); #if 0 xmlSchematronSetValidErrors(ctxt, (xmlSchematronValidityErrorFunc) fprintf, (xmlSchematronValidityWarningFunc) fprintf, stderr); #endif ret = xmlSchematronValidateDoc(ctxt, doc); if (ret == 0) { fprintf(stderr, "%s validates\n", filename); } else if (ret > 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } xmlSchematronFreeValidCtxt(ctxt); if ((timing) && (!repeat)) { endTimer("Validating"); } } #endif #ifdef LIBXML_SCHEMAS_ENABLED if (relaxngschemas != NULL) { xmlRelaxNGValidCtxtPtr ctxt; int ret; if ((timing) && (!repeat)) { startTimer(); } ctxt = xmlRelaxNGNewValidCtxt(relaxngschemas); xmlRelaxNGSetValidErrors(ctxt, (xmlRelaxNGValidityErrorFunc) fprintf, (xmlRelaxNGValidityWarningFunc) fprintf, stderr); ret = xmlRelaxNGValidateDoc(ctxt, doc); if (ret == 0) { fprintf(stderr, "%s validates\n", filename); } else if (ret > 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } xmlRelaxNGFreeValidCtxt(ctxt); if ((timing) && (!repeat)) { endTimer("Validating"); } } else if (wxschemas != NULL) { xmlSchemaValidCtxtPtr ctxt; int ret; if ((timing) && (!repeat)) { startTimer(); } ctxt = xmlSchemaNewValidCtxt(wxschemas); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0) { fprintf(stderr, "%s validates\n", filename); } else if (ret > 0) { fprintf(stderr, "%s fails to validate\n", filename); progresult = XMLLINT_ERR_VALID; } else { fprintf(stderr, "%s validation generated an internal error\n", filename); progresult = XMLLINT_ERR_VALID; } xmlSchemaFreeValidCtxt(ctxt); if ((timing) && (!repeat)) { endTimer("Validating"); } } #endif #ifdef LIBXML_DEBUG_ENABLED if ((debugent) && (!html)) xmlDebugDumpEntities(stderr, doc); #endif /* * free it. */ if ((timing) && (!repeat)) { startTimer(); } xmlFreeDoc(doc); if ((timing) && (!repeat)) { endTimer("Freeing"); } } /************************************************************************ * * * Usage and Main * * * ************************************************************************/ static void showVersion(const char *name) { fprintf(stderr, "%s: using libxml version %s\n", name, xmlParserVersion); fprintf(stderr, " compiled with: "); if (xmlHasFeature(XML_WITH_THREAD)) fprintf(stderr, "Threads "); if (xmlHasFeature(XML_WITH_TREE)) fprintf(stderr, "Tree "); if (xmlHasFeature(XML_WITH_OUTPUT)) fprintf(stderr, "Output "); if (xmlHasFeature(XML_WITH_PUSH)) fprintf(stderr, "Push "); if (xmlHasFeature(XML_WITH_READER)) fprintf(stderr, "Reader "); if (xmlHasFeature(XML_WITH_PATTERN)) fprintf(stderr, "Patterns "); if (xmlHasFeature(XML_WITH_WRITER)) fprintf(stderr, "Writer "); if (xmlHasFeature(XML_WITH_SAX1)) fprintf(stderr, "SAXv1 "); if (xmlHasFeature(XML_WITH_FTP)) fprintf(stderr, "FTP "); if (xmlHasFeature(XML_WITH_HTTP)) fprintf(stderr, "HTTP "); if (xmlHasFeature(XML_WITH_VALID)) fprintf(stderr, "DTDValid "); if (xmlHasFeature(XML_WITH_HTML)) fprintf(stderr, "HTML "); if (xmlHasFeature(XML_WITH_LEGACY)) fprintf(stderr, "Legacy "); if (xmlHasFeature(XML_WITH_C14N)) fprintf(stderr, "C14N "); if (xmlHasFeature(XML_WITH_CATALOG)) fprintf(stderr, "Catalog "); if (xmlHasFeature(XML_WITH_XPATH)) fprintf(stderr, "XPath "); if (xmlHasFeature(XML_WITH_XPTR)) fprintf(stderr, "XPointer "); if (xmlHasFeature(XML_WITH_XINCLUDE)) fprintf(stderr, "XInclude "); if (xmlHasFeature(XML_WITH_ICONV)) fprintf(stderr, "Iconv "); if (xmlHasFeature(XML_WITH_ISO8859X)) fprintf(stderr, "ISO8859X "); if (xmlHasFeature(XML_WITH_UNICODE)) fprintf(stderr, "Unicode "); if (xmlHasFeature(XML_WITH_REGEXP)) fprintf(stderr, "Regexps "); if (xmlHasFeature(XML_WITH_AUTOMATA)) fprintf(stderr, "Automata "); if (xmlHasFeature(XML_WITH_EXPR)) fprintf(stderr, "Expr "); if (xmlHasFeature(XML_WITH_SCHEMAS)) fprintf(stderr, "Schemas "); if (xmlHasFeature(XML_WITH_SCHEMATRON)) fprintf(stderr, "Schematron "); if (xmlHasFeature(XML_WITH_MODULES)) fprintf(stderr, "Modules "); if (xmlHasFeature(XML_WITH_DEBUG)) fprintf(stderr, "Debug "); if (xmlHasFeature(XML_WITH_DEBUG_MEM)) fprintf(stderr, "MemDebug "); if (xmlHasFeature(XML_WITH_DEBUG_RUN)) fprintf(stderr, "RunDebug "); if (xmlHasFeature(XML_WITH_ZLIB)) fprintf(stderr, "Zlib "); fprintf(stderr, "\n"); } static void usage(const char *name) { printf("Usage : %s [options] XMLfiles ...\n", name); #ifdef LIBXML_OUTPUT_ENABLED printf("\tParse the XML files and output the result of the parsing\n"); #else printf("\tParse the XML files\n"); #endif /* LIBXML_OUTPUT_ENABLED */ printf("\t--version : display the version of the XML library used\n"); #ifdef LIBXML_DEBUG_ENABLED printf("\t--debug : dump a debug tree of the in-memory document\n"); printf("\t--shell : run a navigating shell\n"); printf("\t--debugent : debug the entities defined in the document\n"); #else #ifdef LIBXML_READER_ENABLED printf("\t--debug : dump the nodes content when using --stream\n"); #endif /* LIBXML_READER_ENABLED */ #endif #ifdef LIBXML_TREE_ENABLED printf("\t--copy : used to test the internal copy implementation\n"); #endif /* LIBXML_TREE_ENABLED */ printf("\t--recover : output what was parsable on broken XML documents\n"); printf("\t--noent : substitute entity references by their value\n"); printf("\t--noout : don't output the result tree\n"); printf("\t--path 'paths': provide a set of paths for resources\n"); printf("\t--load-trace : print trace of all external entites loaded\n"); printf("\t--nonet : refuse to fetch DTDs or entities over network\n"); printf("\t--nocompact : do not generate compact text nodes\n"); printf("\t--htmlout : output results as HTML\n"); printf("\t--nowrap : do not put HTML doc wrapper\n"); #ifdef LIBXML_VALID_ENABLED printf("\t--valid : validate the document in addition to std well-formed check\n"); printf("\t--postvalid : do a posteriori validation, i.e after parsing\n"); printf("\t--dtdvalid URL : do a posteriori validation against a given DTD\n"); printf("\t--dtdvalidfpi FPI : same but name the DTD with a Public Identifier\n"); #endif /* LIBXML_VALID_ENABLED */ printf("\t--timing : print some timings\n"); printf("\t--output file or -o file: save to a given file\n"); printf("\t--repeat : repeat 100 times, for timing or profiling\n"); printf("\t--insert : ad-hoc test for valid insertions\n"); #ifdef LIBXML_OUTPUT_ENABLED #ifdef HAVE_ZLIB_H printf("\t--compress : turn on gzip compression of output\n"); #endif #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_HTML_ENABLED printf("\t--html : use the HTML parser\n"); printf("\t--xmlout : force to use the XML serializer when using --html\n"); #endif #ifdef LIBXML_PUSH_ENABLED printf("\t--push : use the push mode of the parser\n"); #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H printf("\t--memory : parse from memory\n"); #endif printf("\t--maxmem nbbytes : limits memory allocation to nbbytes bytes\n"); printf("\t--nowarning : do not emit warnings from parser/validator\n"); printf("\t--noblanks : drop (ignorable?) blanks spaces\n"); printf("\t--nocdata : replace cdata section with text nodes\n"); #ifdef LIBXML_OUTPUT_ENABLED printf("\t--format : reformat/reindent the input\n"); printf("\t--encode encoding : output in the given encoding\n"); printf("\t--dropdtd : remove the DOCTYPE of the input docs\n"); #endif /* LIBXML_OUTPUT_ENABLED */ printf("\t--c14n : save in W3C canonical format (with comments)\n"); printf("\t--exc-c14n : save in W3C exclusive canonical format (with comments)\n"); #ifdef LIBXML_C14N_ENABLED #endif /* LIBXML_C14N_ENABLED */ printf("\t--nsclean : remove redundant namespace declarations\n"); printf("\t--testIO : test user I/O support\n"); #ifdef LIBXML_CATALOG_ENABLED printf("\t--catalogs : use SGML catalogs from $SGML_CATALOG_FILES\n"); printf("\t otherwise XML Catalogs starting from \n"); printf("\t %s are activated by default\n", XML_XML_DEFAULT_CATALOG); printf("\t--nocatalogs: deactivate all catalogs\n"); #endif printf("\t--auto : generate a small doc on the fly\n"); #ifdef LIBXML_XINCLUDE_ENABLED printf("\t--xinclude : do XInclude processing\n"); printf("\t--noxincludenode : same but do not generate XInclude nodes\n"); #endif printf("\t--loaddtd : fetch external DTD\n"); printf("\t--dtdattr : loaddtd + populate the tree with inherited attributes \n"); #ifdef LIBXML_READER_ENABLED printf("\t--stream : use the streaming interface to process very large files\n"); printf("\t--walker : create a reader and walk though the resulting doc\n"); #endif /* LIBXML_READER_ENABLED */ #ifdef LIBXML_PATTERN_ENABLED printf("\t--pattern pattern_value : test the pattern support\n"); #endif printf("\t--chkregister : verify the node registration code\n"); #ifdef LIBXML_SCHEMAS_ENABLED printf("\t--relaxng schema : do RelaxNG validation against the schema\n"); printf("\t--schema schema : do validation against the WXS schema\n"); #endif #ifdef LIBXML_SCHEMATRON_ENABLED printf("\t--schematron schema : do validation against a schematron\n"); #endif #ifdef LIBXML_SAX1_ENABLED printf("\t--sax1: use the old SAX1 interfaces for processing\n"); #endif printf("\t--sax: do not build a tree but work just at the SAX level\n"); printf("\nLibxml project home page: http://xmlsoft.org/\n"); printf("To report bugs or get some help check: http://xmlsoft.org/bugs.html\n"); } static void registerNode(xmlNodePtr node) { node->_private = malloc(sizeof(long)); *(long*)node->_private = (long) 0x81726354; nbregister++; } static void deregisterNode(xmlNodePtr node) { assert(node->_private != NULL); assert(*(long*)node->_private == (long) 0x81726354); free(node->_private); nbregister--; } int main(int argc, char **argv) { int i, acount; int files = 0; int version = 0; const char* indent; if (argc <= 1) { usage(argv[0]); return(1); } LIBXML_TEST_VERSION for (i = 1; i < argc ; i++) { if (!strcmp(argv[i], "-")) break; if (argv[i][0] != '-') continue; if ((!strcmp(argv[i], "-debug")) || (!strcmp(argv[i], "--debug"))) debug++; else #ifdef LIBXML_DEBUG_ENABLED if ((!strcmp(argv[i], "-shell")) || (!strcmp(argv[i], "--shell"))) { shell++; noout = 1; } else #endif #ifdef LIBXML_TREE_ENABLED if ((!strcmp(argv[i], "-copy")) || (!strcmp(argv[i], "--copy"))) copy++; else #endif /* LIBXML_TREE_ENABLED */ if ((!strcmp(argv[i], "-recover")) || (!strcmp(argv[i], "--recover"))) { recovery++; options |= XML_PARSE_RECOVER; } else if ((!strcmp(argv[i], "-noent")) || (!strcmp(argv[i], "--noent"))) { noent++; options |= XML_PARSE_NOENT; } else if ((!strcmp(argv[i], "-nsclean")) || (!strcmp(argv[i], "--nsclean"))) { options |= XML_PARSE_NSCLEAN; } else if ((!strcmp(argv[i], "-nocdata")) || (!strcmp(argv[i], "--nocdata"))) { options |= XML_PARSE_NOCDATA; } else if ((!strcmp(argv[i], "-nodict")) || (!strcmp(argv[i], "--nodict"))) { options |= XML_PARSE_NODICT; } else if ((!strcmp(argv[i], "-version")) || (!strcmp(argv[i], "--version"))) { showVersion(argv[0]); version = 1; } else if ((!strcmp(argv[i], "-noout")) || (!strcmp(argv[i], "--noout"))) noout++; #ifdef LIBXML_OUTPUT_ENABLED else if ((!strcmp(argv[i], "-o")) || (!strcmp(argv[i], "-output")) || (!strcmp(argv[i], "--output"))) { i++; output = argv[i]; } #endif /* LIBXML_OUTPUT_ENABLED */ else if ((!strcmp(argv[i], "-htmlout")) || (!strcmp(argv[i], "--htmlout"))) htmlout++; else if ((!strcmp(argv[i], "-nowrap")) || (!strcmp(argv[i], "--nowrap"))) nowrap++; #ifdef LIBXML_HTML_ENABLED else if ((!strcmp(argv[i], "-html")) || (!strcmp(argv[i], "--html"))) { html++; } else if ((!strcmp(argv[i], "-xmlout")) || (!strcmp(argv[i], "--xmlout"))) { xmlout++; } #endif /* LIBXML_HTML_ENABLED */ else if ((!strcmp(argv[i], "-loaddtd")) || (!strcmp(argv[i], "--loaddtd"))) { loaddtd++; options |= XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-dtdattr")) || (!strcmp(argv[i], "--dtdattr"))) { loaddtd++; dtdattrs++; options |= XML_PARSE_DTDATTR; } #ifdef LIBXML_VALID_ENABLED else if ((!strcmp(argv[i], "-valid")) || (!strcmp(argv[i], "--valid"))) { valid++; options |= XML_PARSE_DTDVALID; } else if ((!strcmp(argv[i], "-postvalid")) || (!strcmp(argv[i], "--postvalid"))) { postvalid++; loaddtd++; options |= XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-dtdvalid")) || (!strcmp(argv[i], "--dtdvalid"))) { i++; dtdvalid = argv[i]; loaddtd++; options |= XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-dtdvalidfpi")) || (!strcmp(argv[i], "--dtdvalidfpi"))) { i++; dtdvalidfpi = argv[i]; loaddtd++; options |= XML_PARSE_DTDLOAD; } #endif /* LIBXML_VALID_ENABLED */ else if ((!strcmp(argv[i], "-dropdtd")) || (!strcmp(argv[i], "--dropdtd"))) dropdtd++; else if ((!strcmp(argv[i], "-insert")) || (!strcmp(argv[i], "--insert"))) insert++; else if ((!strcmp(argv[i], "-timing")) || (!strcmp(argv[i], "--timing"))) timing++; else if ((!strcmp(argv[i], "-auto")) || (!strcmp(argv[i], "--auto"))) generate++; else if ((!strcmp(argv[i], "-repeat")) || (!strcmp(argv[i], "--repeat"))) { if (repeat) repeat *= 10; else repeat = 100; } #ifdef LIBXML_PUSH_ENABLED else if ((!strcmp(argv[i], "-push")) || (!strcmp(argv[i], "--push"))) push++; #endif /* LIBXML_PUSH_ENABLED */ #ifdef HAVE_SYS_MMAN_H else if ((!strcmp(argv[i], "-memory")) || (!strcmp(argv[i], "--memory"))) memory++; #endif else if ((!strcmp(argv[i], "-testIO")) || (!strcmp(argv[i], "--testIO"))) testIO++; #ifdef LIBXML_XINCLUDE_ENABLED else if ((!strcmp(argv[i], "-xinclude")) || (!strcmp(argv[i], "--xinclude"))) { xinclude++; options |= XML_PARSE_XINCLUDE; } else if ((!strcmp(argv[i], "-noxincludenode")) || (!strcmp(argv[i], "--noxincludenode"))) { xinclude++; options |= XML_PARSE_XINCLUDE; options |= XML_PARSE_NOXINCNODE; } #endif #ifdef LIBXML_OUTPUT_ENABLED #ifdef HAVE_ZLIB_H else if ((!strcmp(argv[i], "-compress")) || (!strcmp(argv[i], "--compress"))) { compress++; xmlSetCompressMode(9); } #endif #endif /* LIBXML_OUTPUT_ENABLED */ else if ((!strcmp(argv[i], "-nowarning")) || (!strcmp(argv[i], "--nowarning"))) { xmlGetWarningsDefaultValue = 0; xmlPedanticParserDefault(0); options |= XML_PARSE_NOWARNING; } else if ((!strcmp(argv[i], "-pedantic")) || (!strcmp(argv[i], "--pedantic"))) { xmlGetWarningsDefaultValue = 1; xmlPedanticParserDefault(1); options |= XML_PARSE_PEDANTIC; } #ifdef LIBXML_DEBUG_ENABLED else if ((!strcmp(argv[i], "-debugent")) || (!strcmp(argv[i], "--debugent"))) { debugent++; xmlParserDebugEntities = 1; } #endif #ifdef LIBXML_C14N_ENABLED else if ((!strcmp(argv[i], "-c14n")) || (!strcmp(argv[i], "--c14n"))) { canonical++; options |= XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_DTDLOAD; } else if ((!strcmp(argv[i], "-exc-c14n")) || (!strcmp(argv[i], "--exc-c14n"))) { exc_canonical++; options |= XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_DTDLOAD; } #endif #ifdef LIBXML_CATALOG_ENABLED else if ((!strcmp(argv[i], "-catalogs")) || (!strcmp(argv[i], "--catalogs"))) { catalogs++; } else if ((!strcmp(argv[i], "-nocatalogs")) || (!strcmp(argv[i], "--nocatalogs"))) { nocatalogs++; } #endif else if ((!strcmp(argv[i], "-encode")) || (!strcmp(argv[i], "--encode"))) { i++; encoding = argv[i]; /* * OK it's for testing purposes */ xmlAddEncodingAlias("UTF-8", "DVEnc"); } else if ((!strcmp(argv[i], "-noblanks")) || (!strcmp(argv[i], "--noblanks"))) { noblanks++; xmlKeepBlanksDefault(0); } else if ((!strcmp(argv[i], "-maxmem")) || (!strcmp(argv[i], "--maxmem"))) { i++; if (sscanf(argv[i], "%d", &maxmem) == 1) { xmlMemSetup(myFreeFunc, myMallocFunc, myReallocFunc, myStrdupFunc); } else { maxmem = 0; } } else if ((!strcmp(argv[i], "-format")) || (!strcmp(argv[i], "--format"))) { noblanks++; #ifdef LIBXML_OUTPUT_ENABLED format++; #endif /* LIBXML_OUTPUT_ENABLED */ xmlKeepBlanksDefault(0); } #ifdef LIBXML_READER_ENABLED else if ((!strcmp(argv[i], "-stream")) || (!strcmp(argv[i], "--stream"))) { stream++; } else if ((!strcmp(argv[i], "-walker")) || (!strcmp(argv[i], "--walker"))) { walker++; noout++; } #endif /* LIBXML_READER_ENABLED */ #ifdef LIBXML_SAX1_ENABLED else if ((!strcmp(argv[i], "-sax1")) || (!strcmp(argv[i], "--sax1"))) { sax1++; } #endif /* LIBXML_SAX1_ENABLED */ else if ((!strcmp(argv[i], "-sax")) || (!strcmp(argv[i], "--sax"))) { sax++; } else if ((!strcmp(argv[i], "-chkregister")) || (!strcmp(argv[i], "--chkregister"))) { chkregister++; #ifdef LIBXML_SCHEMAS_ENABLED } else if ((!strcmp(argv[i], "-relaxng")) || (!strcmp(argv[i], "--relaxng"))) { i++; relaxng = argv[i]; noent++; options |= XML_PARSE_NOENT; } else if ((!strcmp(argv[i], "-schema")) || (!strcmp(argv[i], "--schema"))) { i++; schema = argv[i]; noent++; #endif #ifdef LIBXML_SCHEMATRON_ENABLED } else if ((!strcmp(argv[i], "-schematron")) || (!strcmp(argv[i], "--schematron"))) { i++; schematron = argv[i]; noent++; #endif } else if ((!strcmp(argv[i], "-nonet")) || (!strcmp(argv[i], "--nonet"))) { options |= XML_PARSE_NONET; xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader); } else if ((!strcmp(argv[i], "-nocompact")) || (!strcmp(argv[i], "--nocompact"))) { options &= ~XML_PARSE_COMPACT; } else if ((!strcmp(argv[i], "-load-trace")) || (!strcmp(argv[i], "--load-trace"))) { load_trace++; } else if ((!strcmp(argv[i], "-path")) || (!strcmp(argv[i], "--path"))) { i++; parsePath(BAD_CAST argv[i]); #ifdef LIBXML_PATTERN_ENABLED } else if ((!strcmp(argv[i], "-pattern")) || (!strcmp(argv[i], "--pattern"))) { i++; pattern = argv[i]; #endif } else { fprintf(stderr, "Unknown option %s\n", argv[i]); usage(argv[0]); return(1); } } #ifdef LIBXML_CATALOG_ENABLED if (nocatalogs == 0) { if (catalogs) { const char *catal; catal = getenv("SGML_CATALOG_FILES"); if (catal != NULL) { xmlLoadCatalogs(catal); } else { fprintf(stderr, "Variable $SGML_CATALOG_FILES not set\n"); } } } #endif #ifdef LIBXML_SAX1_ENABLED if (sax1) xmlSAXDefaultVersion(1); else xmlSAXDefaultVersion(2); #endif /* LIBXML_SAX1_ENABLED */ if (chkregister) { xmlRegisterNodeDefault(registerNode); xmlDeregisterNodeDefault(deregisterNode); } indent = getenv("XMLLINT_INDENT"); if(indent != NULL) { xmlTreeIndentString = indent; } defaultEntityLoader = xmlGetExternalEntityLoader(); xmlSetExternalEntityLoader(xmllintExternalEntityLoader); xmlLineNumbersDefault(1); if (loaddtd != 0) xmlLoadExtDtdDefaultValue |= XML_DETECT_IDS; if (dtdattrs) xmlLoadExtDtdDefaultValue |= XML_COMPLETE_ATTRS; if (noent != 0) xmlSubstituteEntitiesDefault(1); #ifdef LIBXML_VALID_ENABLED if (valid != 0) xmlDoValidityCheckingDefaultValue = 1; #endif /* LIBXML_VALID_ENABLED */ if ((htmlout) && (!nowrap)) { xmlGenericError(xmlGenericErrorContext, "\n"); xmlGenericError(xmlGenericErrorContext, "%s output\n", argv[0]); xmlGenericError(xmlGenericErrorContext, "

%s output

\n", argv[0]); } #ifdef LIBXML_SCHEMATRON_ENABLED if ((schematron != NULL) && (sax == 0) #ifdef LIBXML_READER_ENABLED && (stream == 0) #endif /* LIBXML_READER_ENABLED */ ) { xmlSchematronParserCtxtPtr ctxt; /* forces loading the DTDs */ xmlLoadExtDtdDefaultValue |= 1; options |= XML_PARSE_DTDLOAD; if (timing) { startTimer(); } ctxt = xmlSchematronNewParserCtxt(schematron); #if 0 xmlSchematronSetParserErrors(ctxt, (xmlSchematronValidityErrorFunc) fprintf, (xmlSchematronValidityWarningFunc) fprintf, stderr); #endif wxschematron = xmlSchematronParse(ctxt); if (wxschematron == NULL) { xmlGenericError(xmlGenericErrorContext, "Schematron schema %s failed to compile\n", schematron); progresult = XMLLINT_ERR_SCHEMACOMP; schematron = NULL; } xmlSchematronFreeParserCtxt(ctxt); if (timing) { endTimer("Compiling the schemas"); } } #endif #ifdef LIBXML_SCHEMAS_ENABLED if ((relaxng != NULL) && (sax == 0) #ifdef LIBXML_READER_ENABLED && (stream == 0) #endif /* LIBXML_READER_ENABLED */ ) { xmlRelaxNGParserCtxtPtr ctxt; /* forces loading the DTDs */ xmlLoadExtDtdDefaultValue |= 1; options |= XML_PARSE_DTDLOAD; if (timing) { startTimer(); } ctxt = xmlRelaxNGNewParserCtxt(relaxng); xmlRelaxNGSetParserErrors(ctxt, (xmlRelaxNGValidityErrorFunc) fprintf, (xmlRelaxNGValidityWarningFunc) fprintf, stderr); relaxngschemas = xmlRelaxNGParse(ctxt); if (relaxngschemas == NULL) { xmlGenericError(xmlGenericErrorContext, "Relax-NG schema %s failed to compile\n", relaxng); progresult = XMLLINT_ERR_SCHEMACOMP; relaxng = NULL; } xmlRelaxNGFreeParserCtxt(ctxt); if (timing) { endTimer("Compiling the schemas"); } } else if ((schema != NULL) #ifdef LIBXML_READER_ENABLED && (stream == 0) #endif ) { xmlSchemaParserCtxtPtr ctxt; if (timing) { startTimer(); } ctxt = xmlSchemaNewParserCtxt(schema); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); wxschemas = xmlSchemaParse(ctxt); if (wxschemas == NULL) { xmlGenericError(xmlGenericErrorContext, "WXS schema %s failed to compile\n", schema); progresult = XMLLINT_ERR_SCHEMACOMP; schema = NULL; } xmlSchemaFreeParserCtxt(ctxt); if (timing) { endTimer("Compiling the schemas"); } } #endif /* LIBXML_SCHEMAS_ENABLED */ #ifdef LIBXML_PATTERN_ENABLED if ((pattern != NULL) #ifdef LIBXML_READER_ENABLED && (walker == 0) #endif ) { patternc = xmlPatterncompile((const xmlChar *) pattern, NULL, 0, NULL); if (patternc == NULL) { xmlGenericError(xmlGenericErrorContext, "Pattern %s failed to compile\n", pattern); progresult = XMLLINT_ERR_SCHEMAPAT; pattern = NULL; } } #endif /* LIBXML_PATTERN_ENABLED */ for (i = 1; i < argc ; i++) { if ((!strcmp(argv[i], "-encode")) || (!strcmp(argv[i], "--encode"))) { i++; continue; } else if ((!strcmp(argv[i], "-o")) || (!strcmp(argv[i], "-output")) || (!strcmp(argv[i], "--output"))) { i++; continue; } #ifdef LIBXML_VALID_ENABLED if ((!strcmp(argv[i], "-dtdvalid")) || (!strcmp(argv[i], "--dtdvalid"))) { i++; continue; } if ((!strcmp(argv[i], "-path")) || (!strcmp(argv[i], "--path"))) { i++; continue; } if ((!strcmp(argv[i], "-dtdvalidfpi")) || (!strcmp(argv[i], "--dtdvalidfpi"))) { i++; continue; } #endif /* LIBXML_VALID_ENABLED */ if ((!strcmp(argv[i], "-relaxng")) || (!strcmp(argv[i], "--relaxng"))) { i++; continue; } if ((!strcmp(argv[i], "-maxmem")) || (!strcmp(argv[i], "--maxmem"))) { i++; continue; } if ((!strcmp(argv[i], "-schema")) || (!strcmp(argv[i], "--schema"))) { i++; continue; } if ((!strcmp(argv[i], "-schematron")) || (!strcmp(argv[i], "--schematron"))) { i++; continue; } #ifdef LIBXML_PATTERN_ENABLED if ((!strcmp(argv[i], "-pattern")) || (!strcmp(argv[i], "--pattern"))) { i++; continue; } #endif if ((timing) && (repeat)) startTimer(); /* Remember file names. "-" means stdin. */ if ((argv[i][0] != '-') || (strcmp(argv[i], "-") == 0)) { if (repeat) { xmlParserCtxtPtr ctxt = NULL; for (acount = 0;acount < repeat;acount++) { #ifdef LIBXML_READER_ENABLED if (stream != 0) { streamFile(argv[i]); } else { #endif /* LIBXML_READER_ENABLED */ if (sax) { testSAX(argv[i]); } else { if (ctxt == NULL) ctxt = xmlNewParserCtxt(); parseAndPrintFile(argv[i], ctxt); } #ifdef LIBXML_READER_ENABLED } #endif /* LIBXML_READER_ENABLED */ } if (ctxt != NULL) xmlFreeParserCtxt(ctxt); } else { nbregister = 0; #ifdef LIBXML_READER_ENABLED if (stream != 0) streamFile(argv[i]); else #endif /* LIBXML_READER_ENABLED */ if (sax) { testSAX(argv[i]); } else { parseAndPrintFile(argv[i], NULL); } if ((chkregister) && (nbregister != 0)) { fprintf(stderr, "Registration count off: %d\n", nbregister); progresult = XMLLINT_ERR_RDREGIS; } } files ++; if ((timing) && (repeat)) { endTimer("%d iterations", repeat); } } } if (generate) parseAndPrintFile(NULL, NULL); if ((htmlout) && (!nowrap)) { xmlGenericError(xmlGenericErrorContext, "\n"); } if ((files == 0) && (!generate) && (version == 0)) { usage(argv[0]); } #ifdef LIBXML_SCHEMATRON_ENABLED if (wxschematron != NULL) xmlSchematronFree(wxschematron); #endif #ifdef LIBXML_SCHEMAS_ENABLED if (relaxngschemas != NULL) xmlRelaxNGFree(relaxngschemas); if (wxschemas != NULL) xmlSchemaFree(wxschemas); xmlRelaxNGCleanupTypes(); #endif #ifdef LIBXML_PATTERN_ENABLED if (patternc != NULL) xmlFreePattern(patternc); #endif xmlCleanupParser(); xmlMemoryDump(); return(progresult); } xdmf-2.1.dfsg.1/Utilities/vtklibxml2/triop.h0000644000175000017500000001315011606020250022074 0ustar amckinstryamckinstry/************************************************************************* * * Id: triop.h 1886 2003-04-03 15:28:28Z veillard * * Copyright (C) 2000 Bjorn Reese and Daniel Stenberg. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER. * ************************************************************************ * * Private functions, types, etc. used for callback functions. * * The ref pointer is an opaque type and should remain as such. * Private data must only be accessible through the getter and * setter functions. * ************************************************************************/ #ifndef TRIO_TRIOP_H #define TRIO_TRIOP_H #include "triodef.h" #include #if defined(TRIO_COMPILER_ANCIENT) # include #else # include #endif #ifdef __cplusplus extern "C" { #endif #ifndef TRIO_C99 # define TRIO_C99 1 #endif #ifndef TRIO_BSD # define TRIO_BSD 1 #endif #ifndef TRIO_GNU # define TRIO_GNU 1 #endif #ifndef TRIO_MISC # define TRIO_MISC 1 #endif #ifndef TRIO_UNIX98 # define TRIO_UNIX98 1 #endif #ifndef TRIO_MICROSOFT # define TRIO_MICROSOFT 1 #endif #ifndef TRIO_EXTENSION # define TRIO_EXTENSION 1 #endif #ifndef TRIO_WIDECHAR /* Does not work yet. Do not enable */ # define TRIO_WIDECHAR 0 #endif #ifndef TRIO_ERRORS # define TRIO_ERRORS 1 #endif #ifndef TRIO_MALLOC # define TRIO_MALLOC(n) malloc(n) #endif #ifndef TRIO_REALLOC # define TRIO_REALLOC(x,n) realloc((x),(n)) #endif #ifndef TRIO_FREE # define TRIO_FREE(x) free(x) #endif /************************************************************************* * User-defined specifiers */ typedef int (*trio_callback_t) TRIO_PROTO((trio_pointer_t)); trio_pointer_t trio_register TRIO_PROTO((trio_callback_t callback, const char *name)); void trio_unregister TRIO_PROTO((trio_pointer_t handle)); TRIO_CONST char *trio_get_format TRIO_PROTO((trio_pointer_t ref)); trio_pointer_t trio_get_argument TRIO_PROTO((trio_pointer_t ref)); /* Modifiers */ int trio_get_width TRIO_PROTO((trio_pointer_t ref)); void trio_set_width TRIO_PROTO((trio_pointer_t ref, int width)); int trio_get_precision TRIO_PROTO((trio_pointer_t ref)); void trio_set_precision TRIO_PROTO((trio_pointer_t ref, int precision)); int trio_get_base TRIO_PROTO((trio_pointer_t ref)); void trio_set_base TRIO_PROTO((trio_pointer_t ref, int base)); int trio_get_padding TRIO_PROTO((trio_pointer_t ref)); void trio_set_padding TRIO_PROTO((trio_pointer_t ref, int is_padding)); int trio_get_short TRIO_PROTO((trio_pointer_t ref)); /* h */ void trio_set_shortshort TRIO_PROTO((trio_pointer_t ref, int is_shortshort)); int trio_get_shortshort TRIO_PROTO((trio_pointer_t ref)); /* hh */ void trio_set_short TRIO_PROTO((trio_pointer_t ref, int is_short)); int trio_get_long TRIO_PROTO((trio_pointer_t ref)); /* l */ void trio_set_long TRIO_PROTO((trio_pointer_t ref, int is_long)); int trio_get_longlong TRIO_PROTO((trio_pointer_t ref)); /* ll */ void trio_set_longlong TRIO_PROTO((trio_pointer_t ref, int is_longlong)); int trio_get_longdouble TRIO_PROTO((trio_pointer_t ref)); /* L */ void trio_set_longdouble TRIO_PROTO((trio_pointer_t ref, int is_longdouble)); int trio_get_alternative TRIO_PROTO((trio_pointer_t ref)); /* # */ void trio_set_alternative TRIO_PROTO((trio_pointer_t ref, int is_alternative)); int trio_get_alignment TRIO_PROTO((trio_pointer_t ref)); /* - */ void trio_set_alignment TRIO_PROTO((trio_pointer_t ref, int is_leftaligned)); int trio_get_spacing TRIO_PROTO((trio_pointer_t ref)); /* TRIO_PROTO((space) */ void trio_set_spacing TRIO_PROTO((trio_pointer_t ref, int is_space)); int trio_get_sign TRIO_PROTO((trio_pointer_t ref)); /* + */ void trio_set_sign TRIO_PROTO((trio_pointer_t ref, int is_showsign)); int trio_get_quote TRIO_PROTO((trio_pointer_t ref)); /* ' */ void trio_set_quote TRIO_PROTO((trio_pointer_t ref, int is_quote)); int trio_get_upper TRIO_PROTO((trio_pointer_t ref)); void trio_set_upper TRIO_PROTO((trio_pointer_t ref, int is_upper)); #if TRIO_C99 int trio_get_largest TRIO_PROTO((trio_pointer_t ref)); /* j */ void trio_set_largest TRIO_PROTO((trio_pointer_t ref, int is_largest)); int trio_get_ptrdiff TRIO_PROTO((trio_pointer_t ref)); /* t */ void trio_set_ptrdiff TRIO_PROTO((trio_pointer_t ref, int is_ptrdiff)); int trio_get_size TRIO_PROTO((trio_pointer_t ref)); /* z / Z */ void trio_set_size TRIO_PROTO((trio_pointer_t ref, int is_size)); #endif /* Printing */ int trio_print_ref TRIO_PROTO((trio_pointer_t ref, const char *format, ...)); int trio_vprint_ref TRIO_PROTO((trio_pointer_t ref, const char *format, va_list args)); int trio_printv_ref TRIO_PROTO((trio_pointer_t ref, const char *format, trio_pointer_t *args)); void trio_print_int TRIO_PROTO((trio_pointer_t ref, int number)); void trio_print_uint TRIO_PROTO((trio_pointer_t ref, unsigned int number)); /* void trio_print_long TRIO_PROTO((trio_pointer_t ref, long number)); */ /* void trio_print_ulong TRIO_PROTO((trio_pointer_t ref, unsigned long number)); */ void trio_print_double TRIO_PROTO((trio_pointer_t ref, double number)); void trio_print_string TRIO_PROTO((trio_pointer_t ref, char *string)); void trio_print_pointer TRIO_PROTO((trio_pointer_t ref, trio_pointer_t pointer)); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* TRIO_TRIOP_H */ xdmf-2.1.dfsg.1/Utilities/vtklibxml2/legacy.c0000644000175000017500000011442611606020250022206 0ustar amckinstryamckinstry/* * legacy.c: set of deprecated routines, not to be used anymore but * kept purely for ABI compatibility * * See Copyright for the status of this software. * * daniel@veillard.com */ #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_LEGACY_ENABLED #include #include #include #include #include #include void xmlUpgradeOldNs(xmlDocPtr doc); /************************************************************************ * * * Deprecated functions kept for compatibility * * * ************************************************************************/ #ifdef LIBXML_HTML_ENABLED xmlChar *htmlDecodeEntities(htmlParserCtxtPtr ctxt, int len, xmlChar end, xmlChar end2, xmlChar end3); /** * htmlDecodeEntities: * @ctxt: the parser context * @len: the len to decode (in bytes !), -1 for no size limit * @end: an end marker xmlChar, 0 if none * @end2: an end marker xmlChar, 0 if none * @end3: an end marker xmlChar, 0 if none * * Substitute the HTML entities by their value * * DEPRECATED !!!! * * Returns A newly allocated string with the substitution done. The caller * must deallocate it ! */ xmlChar * htmlDecodeEntities(htmlParserCtxtPtr ctxt ATTRIBUTE_UNUSED, int len ATTRIBUTE_UNUSED, xmlChar end ATTRIBUTE_UNUSED, xmlChar end2 ATTRIBUTE_UNUSED, xmlChar end3 ATTRIBUTE_UNUSED) { static int deprecated = 0; if (!deprecated) { xmlGenericError(xmlGenericErrorContext, "htmlDecodeEntities() deprecated function reached\n"); deprecated = 1; } return (NULL); } #endif /** * xmlInitializePredefinedEntities: * * Set up the predefined entities. * Deprecated call */ void xmlInitializePredefinedEntities(void) { } /** * xmlCleanupPredefinedEntities: * * Cleanup up the predefined entities table. * Deprecated call */ void xmlCleanupPredefinedEntities(void) { } static const char *xmlFeaturesList[] = { "validate", "load subset", "keep blanks", "disable SAX", "fetch external entities", "substitute entities", "gather line info", "user data", "is html", "is standalone", "stop parser", "document", "is well formed", "is valid", "SAX block", "SAX function internalSubset", "SAX function isStandalone", "SAX function hasInternalSubset", "SAX function hasExternalSubset", "SAX function resolveEntity", "SAX function getEntity", "SAX function entityDecl", "SAX function notationDecl", "SAX function attributeDecl", "SAX function elementDecl", "SAX function unparsedEntityDecl", "SAX function setDocumentLocator", "SAX function startDocument", "SAX function endDocument", "SAX function startElement", "SAX function endElement", "SAX function reference", "SAX function characters", "SAX function ignorableWhitespace", "SAX function processingInstruction", "SAX function comment", "SAX function warning", "SAX function error", "SAX function fatalError", "SAX function getParameterEntity", "SAX function cdataBlock", "SAX function externalSubset", }; /** * xmlGetFeaturesList: * @len: the length of the features name array (input/output) * @result: an array of string to be filled with the features name. * * Copy at most *@len feature names into the @result array * * Returns -1 in case or error, or the total number of features, * len is updated with the number of strings copied, * strings must not be deallocated */ int xmlGetFeaturesList(int *len, const char **result) { int ret, i; ret = sizeof(xmlFeaturesList) / sizeof(xmlFeaturesList[0]); if ((len == NULL) || (result == NULL)) return (ret); if ((*len < 0) || (*len >= 1000)) return (-1); if (*len > ret) *len = ret; for (i = 0; i < *len; i++) result[i] = xmlFeaturesList[i]; return (ret); } /** * xmlGetFeature: * @ctxt: an XML/HTML parser context * @name: the feature name * @result: location to store the result * * Read the current value of one feature of this parser instance * * Returns -1 in case or error, 0 otherwise */ int xmlGetFeature(xmlParserCtxtPtr ctxt, const char *name, void *result) { if ((ctxt == NULL) || (name == NULL) || (result == NULL)) return (-1); if (!strcmp(name, "validate")) { *((int *) result) = ctxt->validate; } else if (!strcmp(name, "keep blanks")) { *((int *) result) = ctxt->keepBlanks; } else if (!strcmp(name, "disable SAX")) { *((int *) result) = ctxt->disableSAX; } else if (!strcmp(name, "fetch external entities")) { *((int *) result) = ctxt->loadsubset; } else if (!strcmp(name, "substitute entities")) { *((int *) result) = ctxt->replaceEntities; } else if (!strcmp(name, "gather line info")) { *((int *) result) = ctxt->record_info; } else if (!strcmp(name, "user data")) { *((void **) result) = ctxt->userData; } else if (!strcmp(name, "is html")) { *((int *) result) = ctxt->html; } else if (!strcmp(name, "is standalone")) { *((int *) result) = ctxt->standalone; } else if (!strcmp(name, "document")) { *((xmlDocPtr *) result) = ctxt->myDoc; } else if (!strcmp(name, "is well formed")) { *((int *) result) = ctxt->wellFormed; } else if (!strcmp(name, "is valid")) { *((int *) result) = ctxt->valid; } else if (!strcmp(name, "SAX block")) { *((xmlSAXHandlerPtr *) result) = ctxt->sax; } else if (!strcmp(name, "SAX function internalSubset")) { *((internalSubsetSAXFunc *) result) = ctxt->sax->internalSubset; } else if (!strcmp(name, "SAX function isStandalone")) { *((isStandaloneSAXFunc *) result) = ctxt->sax->isStandalone; } else if (!strcmp(name, "SAX function hasInternalSubset")) { *((hasInternalSubsetSAXFunc *) result) = ctxt->sax->hasInternalSubset; } else if (!strcmp(name, "SAX function hasExternalSubset")) { *((hasExternalSubsetSAXFunc *) result) = ctxt->sax->hasExternalSubset; } else if (!strcmp(name, "SAX function resolveEntity")) { *((resolveEntitySAXFunc *) result) = ctxt->sax->resolveEntity; } else if (!strcmp(name, "SAX function getEntity")) { *((getEntitySAXFunc *) result) = ctxt->sax->getEntity; } else if (!strcmp(name, "SAX function entityDecl")) { *((entityDeclSAXFunc *) result) = ctxt->sax->entityDecl; } else if (!strcmp(name, "SAX function notationDecl")) { *((notationDeclSAXFunc *) result) = ctxt->sax->notationDecl; } else if (!strcmp(name, "SAX function attributeDecl")) { *((attributeDeclSAXFunc *) result) = ctxt->sax->attributeDecl; } else if (!strcmp(name, "SAX function elementDecl")) { *((elementDeclSAXFunc *) result) = ctxt->sax->elementDecl; } else if (!strcmp(name, "SAX function unparsedEntityDecl")) { *((unparsedEntityDeclSAXFunc *) result) = ctxt->sax->unparsedEntityDecl; } else if (!strcmp(name, "SAX function setDocumentLocator")) { *((setDocumentLocatorSAXFunc *) result) = ctxt->sax->setDocumentLocator; } else if (!strcmp(name, "SAX function startDocument")) { *((startDocumentSAXFunc *) result) = ctxt->sax->startDocument; } else if (!strcmp(name, "SAX function endDocument")) { *((endDocumentSAXFunc *) result) = ctxt->sax->endDocument; } else if (!strcmp(name, "SAX function startElement")) { *((startElementSAXFunc *) result) = ctxt->sax->startElement; } else if (!strcmp(name, "SAX function endElement")) { *((endElementSAXFunc *) result) = ctxt->sax->endElement; } else if (!strcmp(name, "SAX function reference")) { *((referenceSAXFunc *) result) = ctxt->sax->reference; } else if (!strcmp(name, "SAX function characters")) { *((charactersSAXFunc *) result) = ctxt->sax->characters; } else if (!strcmp(name, "SAX function ignorableWhitespace")) { *((ignorableWhitespaceSAXFunc *) result) = ctxt->sax->ignorableWhitespace; } else if (!strcmp(name, "SAX function processingInstruction")) { *((processingInstructionSAXFunc *) result) = ctxt->sax->processingInstruction; } else if (!strcmp(name, "SAX function comment")) { *((commentSAXFunc *) result) = ctxt->sax->comment; } else if (!strcmp(name, "SAX function warning")) { *((warningSAXFunc *) result) = ctxt->sax->warning; } else if (!strcmp(name, "SAX function error")) { *((errorSAXFunc *) result) = ctxt->sax->error; } else if (!strcmp(name, "SAX function fatalError")) { *((fatalErrorSAXFunc *) result) = ctxt->sax->fatalError; } else if (!strcmp(name, "SAX function getParameterEntity")) { *((getParameterEntitySAXFunc *) result) = ctxt->sax->getParameterEntity; } else if (!strcmp(name, "SAX function cdataBlock")) { *((cdataBlockSAXFunc *) result) = ctxt->sax->cdataBlock; } else if (!strcmp(name, "SAX function externalSubset")) { *((externalSubsetSAXFunc *) result) = ctxt->sax->externalSubset; } else { return (-1); } return (0); } /** * xmlSetFeature: * @ctxt: an XML/HTML parser context * @name: the feature name * @value: pointer to the location of the new value * * Change the current value of one feature of this parser instance * * Returns -1 in case or error, 0 otherwise */ int xmlSetFeature(xmlParserCtxtPtr ctxt, const char *name, void *value) { if ((ctxt == NULL) || (name == NULL) || (value == NULL)) return (-1); if (!strcmp(name, "validate")) { int newvalidate = *((int *) value); if ((!ctxt->validate) && (newvalidate != 0)) { if (ctxt->vctxt.warning == NULL) ctxt->vctxt.warning = xmlParserValidityWarning; if (ctxt->vctxt.error == NULL) ctxt->vctxt.error = xmlParserValidityError; ctxt->vctxt.nodeMax = 0; } ctxt->validate = newvalidate; } else if (!strcmp(name, "keep blanks")) { ctxt->keepBlanks = *((int *) value); } else if (!strcmp(name, "disable SAX")) { ctxt->disableSAX = *((int *) value); } else if (!strcmp(name, "fetch external entities")) { ctxt->loadsubset = *((int *) value); } else if (!strcmp(name, "substitute entities")) { ctxt->replaceEntities = *((int *) value); } else if (!strcmp(name, "gather line info")) { ctxt->record_info = *((int *) value); } else if (!strcmp(name, "user data")) { ctxt->userData = *((void **) value); } else if (!strcmp(name, "is html")) { ctxt->html = *((int *) value); } else if (!strcmp(name, "is standalone")) { ctxt->standalone = *((int *) value); } else if (!strcmp(name, "document")) { ctxt->myDoc = *((xmlDocPtr *) value); } else if (!strcmp(name, "is well formed")) { ctxt->wellFormed = *((int *) value); } else if (!strcmp(name, "is valid")) { ctxt->valid = *((int *) value); } else if (!strcmp(name, "SAX block")) { ctxt->sax = *((xmlSAXHandlerPtr *) value); } else if (!strcmp(name, "SAX function internalSubset")) { ctxt->sax->internalSubset = *((internalSubsetSAXFunc *) value); } else if (!strcmp(name, "SAX function isStandalone")) { ctxt->sax->isStandalone = *((isStandaloneSAXFunc *) value); } else if (!strcmp(name, "SAX function hasInternalSubset")) { ctxt->sax->hasInternalSubset = *((hasInternalSubsetSAXFunc *) value); } else if (!strcmp(name, "SAX function hasExternalSubset")) { ctxt->sax->hasExternalSubset = *((hasExternalSubsetSAXFunc *) value); } else if (!strcmp(name, "SAX function resolveEntity")) { ctxt->sax->resolveEntity = *((resolveEntitySAXFunc *) value); } else if (!strcmp(name, "SAX function getEntity")) { ctxt->sax->getEntity = *((getEntitySAXFunc *) value); } else if (!strcmp(name, "SAX function entityDecl")) { ctxt->sax->entityDecl = *((entityDeclSAXFunc *) value); } else if (!strcmp(name, "SAX function notationDecl")) { ctxt->sax->notationDecl = *((notationDeclSAXFunc *) value); } else if (!strcmp(name, "SAX function attributeDecl")) { ctxt->sax->attributeDecl = *((attributeDeclSAXFunc *) value); } else if (!strcmp(name, "SAX function elementDecl")) { ctxt->sax->elementDecl = *((elementDeclSAXFunc *) value); } else if (!strcmp(name, "SAX function unparsedEntityDecl")) { ctxt->sax->unparsedEntityDecl = *((unparsedEntityDeclSAXFunc *) value); } else if (!strcmp(name, "SAX function setDocumentLocator")) { ctxt->sax->setDocumentLocator = *((setDocumentLocatorSAXFunc *) value); } else if (!strcmp(name, "SAX function startDocument")) { ctxt->sax->startDocument = *((startDocumentSAXFunc *) value); } else if (!strcmp(name, "SAX function endDocument")) { ctxt->sax->endDocument = *((endDocumentSAXFunc *) value); } else if (!strcmp(name, "SAX function startElement")) { ctxt->sax->startElement = *((startElementSAXFunc *) value); } else if (!strcmp(name, "SAX function endElement")) { ctxt->sax->endElement = *((endElementSAXFunc *) value); } else if (!strcmp(name, "SAX function reference")) { ctxt->sax->reference = *((referenceSAXFunc *) value); } else if (!strcmp(name, "SAX function characters")) { ctxt->sax->characters = *((charactersSAXFunc *) value); } else if (!strcmp(name, "SAX function ignorableWhitespace")) { ctxt->sax->ignorableWhitespace = *((ignorableWhitespaceSAXFunc *) value); } else if (!strcmp(name, "SAX function processingInstruction")) { ctxt->sax->processingInstruction = *((processingInstructionSAXFunc *) value); } else if (!strcmp(name, "SAX function comment")) { ctxt->sax->comment = *((commentSAXFunc *) value); } else if (!strcmp(name, "SAX function warning")) { ctxt->sax->warning = *((warningSAXFunc *) value); } else if (!strcmp(name, "SAX function error")) { ctxt->sax->error = *((errorSAXFunc *) value); } else if (!strcmp(name, "SAX function fatalError")) { ctxt->sax->fatalError = *((fatalErrorSAXFunc *) value); } else if (!strcmp(name, "SAX function getParameterEntity")) { ctxt->sax->getParameterEntity = *((getParameterEntitySAXFunc *) value); } else if (!strcmp(name, "SAX function cdataBlock")) { ctxt->sax->cdataBlock = *((cdataBlockSAXFunc *) value); } else if (!strcmp(name, "SAX function externalSubset")) { ctxt->sax->externalSubset = *((externalSubsetSAXFunc *) value); } else { return (-1); } return (0); } /** * xmlDecodeEntities: * @ctxt: the parser context * @len: the len to decode (in bytes !), -1 for no size limit * @what: combination of XML_SUBSTITUTE_REF and XML_SUBSTITUTE_PEREF * @end: an end marker xmlChar, 0 if none * @end2: an end marker xmlChar, 0 if none * @end3: an end marker xmlChar, 0 if none * * This function is deprecated, we now always process entities content * through xmlStringDecodeEntities * * TODO: remove it in next major release. * * [67] Reference ::= EntityRef | CharRef * * [69] PEReference ::= '%' Name ';' * * Returns A newly allocated string with the substitution done. The caller * must deallocate it ! */ xmlChar * xmlDecodeEntities(xmlParserCtxtPtr ctxt ATTRIBUTE_UNUSED, int len ATTRIBUTE_UNUSED, int what ATTRIBUTE_UNUSED, xmlChar end ATTRIBUTE_UNUSED, xmlChar end2 ATTRIBUTE_UNUSED, xmlChar end3 ATTRIBUTE_UNUSED) { static int deprecated = 0; if (!deprecated) { xmlGenericError(xmlGenericErrorContext, "xmlDecodeEntities() deprecated function reached\n"); deprecated = 1; } return (NULL); } /** * xmlNamespaceParseNCName: * @ctxt: an XML parser context * * parse an XML namespace name. * * TODO: this seems not in use anymore, the namespace handling is done on * top of the SAX interfaces, i.e. not on raw input. * * [NS 3] NCName ::= (Letter | '_') (NCNameChar)* * * [NS 4] NCNameChar ::= Letter | Digit | '.' | '-' | '_' | * CombiningChar | Extender * * Returns the namespace name or NULL */ xmlChar * xmlNamespaceParseNCName(xmlParserCtxtPtr ctxt ATTRIBUTE_UNUSED) { static int deprecated = 0; if (!deprecated) { xmlGenericError(xmlGenericErrorContext, "xmlNamespaceParseNCName() deprecated function reached\n"); deprecated = 1; } return (NULL); } /** * xmlNamespaceParseQName: * @ctxt: an XML parser context * @prefix: a xmlChar ** * * TODO: this seems not in use anymore, the namespace handling is done on * top of the SAX interfaces, i.e. not on raw input. * * parse an XML qualified name * * [NS 5] QName ::= (Prefix ':')? LocalPart * * [NS 6] Prefix ::= NCName * * [NS 7] LocalPart ::= NCName * * Returns the local part, and prefix is updated * to get the Prefix if any. */ xmlChar * xmlNamespaceParseQName(xmlParserCtxtPtr ctxt ATTRIBUTE_UNUSED, xmlChar ** prefix ATTRIBUTE_UNUSED) { static int deprecated = 0; if (!deprecated) { xmlGenericError(xmlGenericErrorContext, "xmlNamespaceParseQName() deprecated function reached\n"); deprecated = 1; } return (NULL); } /** * xmlNamespaceParseNSDef: * @ctxt: an XML parser context * * parse a namespace prefix declaration * * TODO: this seems not in use anymore, the namespace handling is done on * top of the SAX interfaces, i.e. not on raw input. * * [NS 1] NSDef ::= PrefixDef Eq SystemLiteral * * [NS 2] PrefixDef ::= 'xmlns' (':' NCName)? * * Returns the namespace name */ xmlChar * xmlNamespaceParseNSDef(xmlParserCtxtPtr ctxt ATTRIBUTE_UNUSED) { static int deprecated = 0; if (!deprecated) { xmlGenericError(xmlGenericErrorContext, "xmlNamespaceParseNSDef() deprecated function reached\n"); deprecated = 1; } return (NULL); } /** * xmlParseQuotedString: * @ctxt: an XML parser context * * Parse and return a string between quotes or doublequotes * * TODO: Deprecated, to be removed at next drop of binary compatibility * * Returns the string parser or NULL. */ xmlChar * xmlParseQuotedString(xmlParserCtxtPtr ctxt ATTRIBUTE_UNUSED) { static int deprecated = 0; if (!deprecated) { xmlGenericError(xmlGenericErrorContext, "xmlParseQuotedString() deprecated function reached\n"); deprecated = 1; } return (NULL); } /** * xmlParseNamespace: * @ctxt: an XML parser context * * xmlParseNamespace: parse specific PI ' * * daniel@veillard.com */ #define IN_LIBXML #include "libxml.h" #include #include #include #include #include /************************************************************************ * * * Commodity functions to handle xmlChars * * * ************************************************************************/ /** * xmlStrndup: * @cur: the input xmlChar * * @len: the len of @cur * * a strndup for array of xmlChar's * * Returns a new xmlChar * or NULL */ xmlChar * xmlStrndup(const xmlChar *cur, int len) { xmlChar *ret; if ((cur == NULL) || (len < 0)) return(NULL); ret = (xmlChar *) xmlMallocAtomic((len + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlErrMemory(NULL, NULL); return(NULL); } memcpy(ret, cur, len * sizeof(xmlChar)); ret[len] = 0; return(ret); } /** * xmlStrdup: * @cur: the input xmlChar * * * a strdup for array of xmlChar's. Since they are supposed to be * encoded in UTF-8 or an encoding with 8bit based chars, we assume * a termination mark of '0'. * * Returns a new xmlChar * or NULL */ xmlChar * xmlStrdup(const xmlChar *cur) { const xmlChar *p = cur; if (cur == NULL) return(NULL); while (*p != 0) p++; /* non input consuming */ return(xmlStrndup(cur, p - cur)); } /** * xmlCharStrndup: * @cur: the input char * * @len: the len of @cur * * a strndup for char's to xmlChar's * * Returns a new xmlChar * or NULL */ xmlChar * xmlCharStrndup(const char *cur, int len) { int i; xmlChar *ret; if ((cur == NULL) || (len < 0)) return(NULL); ret = (xmlChar *) xmlMallocAtomic((len + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlErrMemory(NULL, NULL); return(NULL); } for (i = 0;i < len;i++) { ret[i] = (xmlChar) cur[i]; if (ret[i] == 0) return(ret); } ret[len] = 0; return(ret); } /** * xmlCharStrdup: * @cur: the input char * * * a strdup for char's to xmlChar's * * Returns a new xmlChar * or NULL */ xmlChar * xmlCharStrdup(const char *cur) { const char *p = cur; if (cur == NULL) return(NULL); while (*p != '\0') p++; /* non input consuming */ return(xmlCharStrndup(cur, p - cur)); } /** * xmlStrcmp: * @str1: the first xmlChar * * @str2: the second xmlChar * * * a strcmp for xmlChar's * * Returns the integer result of the comparison */ int xmlStrcmp(const xmlChar *str1, const xmlChar *str2) { register int tmp; if (str1 == str2) return(0); if (str1 == NULL) return(-1); if (str2 == NULL) return(1); do { tmp = *str1++ - *str2; if (tmp != 0) return(tmp); } while (*str2++ != 0); return 0; } /** * xmlStrEqual: * @str1: the first xmlChar * * @str2: the second xmlChar * * * Check if both strings are equal of have same content. * Should be a bit more readable and faster than xmlStrcmp() * * Returns 1 if they are equal, 0 if they are different */ int xmlStrEqual(const xmlChar *str1, const xmlChar *str2) { if (str1 == str2) return(1); if (str1 == NULL) return(0); if (str2 == NULL) return(0); do { if (*str1++ != *str2) return(0); } while (*str2++); return(1); } /** * xmlStrQEqual: * @pref: the prefix of the QName * @name: the localname of the QName * @str: the second xmlChar * * * Check if a QName is Equal to a given string * * Returns 1 if they are equal, 0 if they are different */ int xmlStrQEqual(const xmlChar *pref, const xmlChar *name, const xmlChar *str) { if (pref == NULL) return(xmlStrEqual(name, str)); if (name == NULL) return(0); if (str == NULL) return(0); do { if (*pref++ != *str) return(0); } while ((*str++) && (*pref)); if (*str++ != ':') return(0); do { if (*name++ != *str) return(0); } while (*str++); return(1); } /** * xmlStrncmp: * @str1: the first xmlChar * * @str2: the second xmlChar * * @len: the max comparison length * * a strncmp for xmlChar's * * Returns the integer result of the comparison */ int xmlStrncmp(const xmlChar *str1, const xmlChar *str2, int len) { register int tmp; if (len <= 0) return(0); if (str1 == str2) return(0); if (str1 == NULL) return(-1); if (str2 == NULL) return(1); #ifdef __GNUC__ tmp = strncmp((const char *)str1, (const char *)str2, len); return tmp; #else do { tmp = *str1++ - *str2; if (tmp != 0 || --len == 0) return(tmp); } while (*str2++ != 0); return 0; #endif } static const xmlChar casemap[256] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17, 0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27, 0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, 0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x61,0x62,0x63,0x64,0x65,0x66,0x67, 0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77, 0x78,0x79,0x7A,0x7B,0x5C,0x5D,0x5E,0x5F, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67, 0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77, 0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97, 0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7, 0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7, 0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7, 0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7, 0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7, 0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7, 0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF }; /** * xmlStrcasecmp: * @str1: the first xmlChar * * @str2: the second xmlChar * * * a strcasecmp for xmlChar's * * Returns the integer result of the comparison */ int xmlStrcasecmp(const xmlChar *str1, const xmlChar *str2) { register int tmp; if (str1 == str2) return(0); if (str1 == NULL) return(-1); if (str2 == NULL) return(1); do { tmp = casemap[*str1++] - casemap[*str2]; if (tmp != 0) return(tmp); } while (*str2++ != 0); return 0; } /** * xmlStrncasecmp: * @str1: the first xmlChar * * @str2: the second xmlChar * * @len: the max comparison length * * a strncasecmp for xmlChar's * * Returns the integer result of the comparison */ int xmlStrncasecmp(const xmlChar *str1, const xmlChar *str2, int len) { register int tmp; if (len <= 0) return(0); if (str1 == str2) return(0); if (str1 == NULL) return(-1); if (str2 == NULL) return(1); do { tmp = casemap[*str1++] - casemap[*str2]; if (tmp != 0 || --len == 0) return(tmp); } while (*str2++ != 0); return 0; } /** * xmlStrchr: * @str: the xmlChar * array * @val: the xmlChar to search * * a strchr for xmlChar's * * Returns the xmlChar * for the first occurrence or NULL. */ const xmlChar * xmlStrchr(const xmlChar *str, xmlChar val) { if (str == NULL) return(NULL); while (*str != 0) { /* non input consuming */ if (*str == val) return((xmlChar *) str); str++; } return(NULL); } /** * xmlStrstr: * @str: the xmlChar * array (haystack) * @val: the xmlChar to search (needle) * * a strstr for xmlChar's * * Returns the xmlChar * for the first occurrence or NULL. */ const xmlChar * xmlStrstr(const xmlChar *str, const xmlChar *val) { int n; if (str == NULL) return(NULL); if (val == NULL) return(NULL); n = xmlStrlen(val); if (n == 0) return(str); while (*str != 0) { /* non input consuming */ if (*str == *val) { if (!xmlStrncmp(str, val, n)) return((const xmlChar *) str); } str++; } return(NULL); } /** * xmlStrcasestr: * @str: the xmlChar * array (haystack) * @val: the xmlChar to search (needle) * * a case-ignoring strstr for xmlChar's * * Returns the xmlChar * for the first occurrence or NULL. */ const xmlChar * xmlStrcasestr(const xmlChar *str, xmlChar *val) { int n; if (str == NULL) return(NULL); if (val == NULL) return(NULL); n = xmlStrlen(val); if (n == 0) return(str); while (*str != 0) { /* non input consuming */ if (casemap[*str] == casemap[*val]) if (!xmlStrncasecmp(str, val, n)) return(str); str++; } return(NULL); } /** * xmlStrsub: * @str: the xmlChar * array (haystack) * @start: the index of the first char (zero based) * @len: the length of the substring * * Extract a substring of a given string * * Returns the xmlChar * for the first occurrence or NULL. */ xmlChar * xmlStrsub(const xmlChar *str, int start, int len) { int i; if (str == NULL) return(NULL); if (start < 0) return(NULL); if (len < 0) return(NULL); for (i = 0;i < start;i++) { if (*str == 0) return(NULL); str++; } if (*str == 0) return(NULL); return(xmlStrndup(str, len)); } /** * xmlStrlen: * @str: the xmlChar * array * * length of a xmlChar's string * * Returns the number of xmlChar contained in the ARRAY. */ int xmlStrlen(const xmlChar *str) { int len = 0; if (str == NULL) return(0); while (*str != 0) { /* non input consuming */ str++; len++; } return(len); } /** * xmlStrncat: * @cur: the original xmlChar * array * @add: the xmlChar * array added * @len: the length of @add * * a strncat for array of xmlChar's, it will extend @cur with the len * first bytes of @add. Note that if @len < 0 then this is an API error * and NULL will be returned. * * Returns a new xmlChar *, the original @cur is reallocated if needed * and should not be freed */ xmlChar * xmlStrncat(xmlChar *cur, const xmlChar *add, int len) { int size; xmlChar *ret; if ((add == NULL) || (len == 0)) return(cur); if (len < 0) return(NULL); if (cur == NULL) return(xmlStrndup(add, len)); size = xmlStrlen(cur); ret = (xmlChar *) xmlRealloc(cur, (size + len + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlErrMemory(NULL, NULL); return(cur); } memcpy(&ret[size], add, len * sizeof(xmlChar)); ret[size + len] = 0; return(ret); } /** * xmlStrncatNew: * @str1: first xmlChar string * @str2: second xmlChar string * @len: the len of @str2 or < 0 * * same as xmlStrncat, but creates a new string. The original * two strings are not freed. If @len is < 0 then the length * will be calculated automatically. * * Returns a new xmlChar * or NULL */ xmlChar * xmlStrncatNew(const xmlChar *str1, const xmlChar *str2, int len) { int size; xmlChar *ret; if (len < 0) len = xmlStrlen(str2); if ((str2 == NULL) || (len == 0)) return(xmlStrdup(str1)); if (str1 == NULL) return(xmlStrndup(str2, len)); size = xmlStrlen(str1); ret = (xmlChar *) xmlMalloc((size + len + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlErrMemory(NULL, NULL); return(xmlStrndup(str1, size)); } memcpy(ret, str1, size * sizeof(xmlChar)); memcpy(&ret[size], str2, len * sizeof(xmlChar)); ret[size + len] = 0; return(ret); } /** * xmlStrcat: * @cur: the original xmlChar * array * @add: the xmlChar * array added * * a strcat for array of xmlChar's. Since they are supposed to be * encoded in UTF-8 or an encoding with 8bit based chars, we assume * a termination mark of '0'. * * Returns a new xmlChar * containing the concatenated string. */ xmlChar * xmlStrcat(xmlChar *cur, const xmlChar *add) { const xmlChar *p = add; if (add == NULL) return(cur); if (cur == NULL) return(xmlStrdup(add)); while (*p != 0) p++; /* non input consuming */ return(xmlStrncat(cur, add, p - add)); } /** * xmlStrPrintf: * @buf: the result buffer. * @len: the result buffer length. * @msg: the message with printf formatting. * @...: extra parameters for the message. * * Formats @msg and places result into @buf. * * Returns the number of characters written to @buf or -1 if an error occurs. */ int XMLCDECL xmlStrPrintf(xmlChar *buf, int len, const xmlChar *msg, ...) { va_list args; int ret; if((buf == NULL) || (msg == NULL)) { return(-1); } va_start(args, msg); ret = vsnprintf((char *) buf, len, (const char *) msg, args); va_end(args); buf[len - 1] = 0; /* be safe ! */ return(ret); } /** * xmlStrVPrintf: * @buf: the result buffer. * @len: the result buffer length. * @msg: the message with printf formatting. * @ap: extra parameters for the message. * * Formats @msg and places result into @buf. * * Returns the number of characters written to @buf or -1 if an error occurs. */ int xmlStrVPrintf(xmlChar *buf, int len, const xmlChar *msg, va_list ap) { int ret; if((buf == NULL) || (msg == NULL)) { return(-1); } ret = vsnprintf((char *) buf, len, (const char *) msg, ap); buf[len - 1] = 0; /* be safe ! */ return(ret); } /************************************************************************ * * * Generic UTF8 handling routines * * * * From rfc2044: encoding of the Unicode values on UTF-8: * * * * UCS-4 range (hex.) UTF-8 octet sequence (binary) * * 0000 0000-0000 007F 0xxxxxxx * * 0000 0080-0000 07FF 110xxxxx 10xxxxxx * * 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx * * * * I hope we won't use values > 0xFFFF anytime soon ! * * * ************************************************************************/ /** * xmlUTF8Size: * @utf: pointer to the UTF8 character * * calculates the internal size of a UTF8 character * * returns the numbers of bytes in the character, -1 on format error */ int xmlUTF8Size(const xmlChar *utf) { xmlChar mask; int len; if (utf == NULL) return -1; if (*utf < 0x80) return 1; /* check valid UTF8 character */ if (!(*utf & 0x40)) return -1; /* determine number of bytes in char */ len = 2; for (mask=0x20; mask != 0; mask>>=1) { if (!(*utf & mask)) return len; len++; } return -1; } /** * xmlUTF8Charcmp: * @utf1: pointer to first UTF8 char * @utf2: pointer to second UTF8 char * * compares the two UCS4 values * * returns result of the compare as with xmlStrncmp */ int xmlUTF8Charcmp(const xmlChar *utf1, const xmlChar *utf2) { if (utf1 == NULL ) { if (utf2 == NULL) return 0; return -1; } return xmlStrncmp(utf1, utf2, xmlUTF8Size(utf1)); } /** * xmlUTF8Strlen: * @utf: a sequence of UTF-8 encoded bytes * * compute the length of an UTF8 string, it doesn't do a full UTF8 * checking of the content of the string. * * Returns the number of characters in the string or -1 in case of error */ int xmlUTF8Strlen(const xmlChar *utf) { int ret = 0; if (utf == NULL) return(-1); while (*utf != 0) { if (utf[0] & 0x80) { if ((utf[1] & 0xc0) != 0x80) return(-1); if ((utf[0] & 0xe0) == 0xe0) { if ((utf[2] & 0xc0) != 0x80) return(-1); if ((utf[0] & 0xf0) == 0xf0) { if ((utf[0] & 0xf8) != 0xf0 || (utf[3] & 0xc0) != 0x80) return(-1); utf += 4; } else { utf += 3; } } else { utf += 2; } } else { utf++; } ret++; } return(ret); } /** * xmlGetUTF8Char: * @utf: a sequence of UTF-8 encoded bytes * @len: a pointer to the minimum number of bytes present in * the sequence. This is used to assure the next character * is completely contained within the sequence. * * Read the first UTF8 character from @utf * * Returns the char value or -1 in case of error, and sets *len to * the actual number of bytes consumed (0 in case of error) */ int xmlGetUTF8Char(const unsigned char *utf, int *len) { unsigned int c; if (utf == NULL) goto error; if (len == NULL) goto error; if (*len < 1) goto error; c = utf[0]; if (c & 0x80) { if (*len < 2) goto error; if ((utf[1] & 0xc0) != 0x80) goto error; if ((c & 0xe0) == 0xe0) { if (*len < 3) goto error; if ((utf[2] & 0xc0) != 0x80) goto error; if ((c & 0xf0) == 0xf0) { if (*len < 4) goto error; if ((c & 0xf8) != 0xf0 || (utf[3] & 0xc0) != 0x80) goto error; *len = 4; /* 4-byte code */ c = (utf[0] & 0x7) << 18; c |= (utf[1] & 0x3f) << 12; c |= (utf[2] & 0x3f) << 6; c |= utf[3] & 0x3f; } else { /* 3-byte code */ *len = 3; c = (utf[0] & 0xf) << 12; c |= (utf[1] & 0x3f) << 6; c |= utf[2] & 0x3f; } } else { /* 2-byte code */ *len = 2; c = (utf[0] & 0x1f) << 6; c |= utf[1] & 0x3f; } } else { /* 1-byte code */ *len = 1; } return(c); error: if (len != NULL) *len = 0; return(-1); } /** * xmlCheckUTF8: * @utf: Pointer to putative UTF-8 encoded string. * * Checks @utf for being valid UTF-8. @utf is assumed to be * null-terminated. This function is not super-strict, as it will * allow longer UTF-8 sequences than necessary. Note that Java is * capable of producing these sequences if provoked. Also note, this * routine checks for the 4-byte maximum size, but does not check for * 0x10ffff maximum value. * * Return value: true if @utf is valid. **/ int xmlCheckUTF8(const unsigned char *utf) { int ix; unsigned char c; if (utf == NULL) return(0); /* * utf is a string of 1, 2, 3 or 4 bytes. The valid strings * are as follows (in "bit format"): * 0xxxxxxx valid 1-byte * 110xxxxx 10xxxxxx valid 2-byte * 1110xxxx 10xxxxxx 10xxxxxx valid 3-byte * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx valid 4-byte */ for (ix = 0; (c = utf[ix]);) { /* string is 0-terminated */ if ((c & 0x80) == 0x00) { /* 1-byte code, starts with 10 */ ix++; } else if ((c & 0xe0) == 0xc0) {/* 2-byte code, starts with 110 */ if ((utf[ix+1] & 0xc0 ) != 0x80) return 0; ix += 2; } else if ((c & 0xf0) == 0xe0) {/* 3-byte code, starts with 1110 */ if (((utf[ix+1] & 0xc0) != 0x80) || ((utf[ix+2] & 0xc0) != 0x80)) return 0; ix += 3; } else if ((c & 0xf8) == 0xf0) {/* 4-byte code, starts with 11110 */ if (((utf[ix+1] & 0xc0) != 0x80) || ((utf[ix+2] & 0xc0) != 0x80) || ((utf[ix+3] & 0xc0) != 0x80)) return 0; ix += 4; } else /* unknown encoding */ return 0; } return(1); } /** * xmlUTF8Strsize: * @utf: a sequence of UTF-8 encoded bytes * @len: the number of characters in the array * * storage size of an UTF8 string * the behaviour is not garanteed if the input string is not UTF-8 * * Returns the storage size of * the first 'len' characters of ARRAY */ int xmlUTF8Strsize(const xmlChar *utf, int len) { const xmlChar *ptr=utf; xmlChar ch; if (utf == NULL) return(0); if (len <= 0) return(0); while ( len-- > 0) { if ( !*ptr ) break; if ( (ch = *ptr++) & 0x80) while ((ch<<=1) & 0x80 ) { ptr++; if (*ptr == 0) break; } } return (ptr - utf); } /** * xmlUTF8Strndup: * @utf: the input UTF8 * * @len: the len of @utf (in chars) * * a strndup for array of UTF8's * * Returns a new UTF8 * or NULL */ xmlChar * xmlUTF8Strndup(const xmlChar *utf, int len) { xmlChar *ret; int i; if ((utf == NULL) || (len < 0)) return(NULL); i = xmlUTF8Strsize(utf, len); ret = (xmlChar *) xmlMallocAtomic((i + 1) * sizeof(xmlChar)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "malloc of %ld byte failed\n", (len + 1) * (long)sizeof(xmlChar)); return(NULL); } memcpy(ret, utf, i * sizeof(xmlChar)); ret[i] = 0; return(ret); } /** * xmlUTF8Strpos: * @utf: the input UTF8 * * @pos: the position of the desired UTF8 char (in chars) * * a function to provide the equivalent of fetching a * character from a string array * * Returns a pointer to the UTF8 character or NULL */ const xmlChar * xmlUTF8Strpos(const xmlChar *utf, int pos) { xmlChar ch; if (utf == NULL) return(NULL); if (pos < 0) return(NULL); while (pos--) { if ((ch=*utf++) == 0) return(NULL); if ( ch & 0x80 ) { /* if not simple ascii, verify proper format */ if ( (ch & 0xc0) != 0xc0 ) return(NULL); /* then skip over remaining bytes for this char */ while ( (ch <<= 1) & 0x80 ) if ( (*utf++ & 0xc0) != 0x80 ) return(NULL); } } return((xmlChar *)utf); } /** * xmlUTF8Strloc: * @utf: the input UTF8 * * @utfchar: the UTF8 character to be found * * a function to provide the relative location of a UTF8 char * * Returns the relative character position of the desired char * or -1 if not found */ int xmlUTF8Strloc(const xmlChar *utf, const xmlChar *utfchar) { int i, size; xmlChar ch; if (utf==NULL || utfchar==NULL) return -1; size = xmlUTF8Strsize(utfchar, 1); for(i=0; (ch=*utf) != 0; i++) { if (xmlStrncmp(utf, utfchar, size)==0) return(i); utf++; if ( ch & 0x80 ) { /* if not simple ascii, verify proper format */ if ( (ch & 0xc0) != 0xc0 ) return(-1); /* then skip over remaining bytes for this char */ while ( (ch <<= 1) & 0x80 ) if ( (*utf++ & 0xc0) != 0x80 ) return(-1); } } return(-1); } /** * xmlUTF8Strsub: * @utf: a sequence of UTF-8 encoded bytes * @start: relative pos of first char * @len: total number to copy * * Create a substring from a given UTF-8 string * Note: positions are given in units of UTF-8 chars * * Returns a pointer to a newly created string * or NULL if any problem */ xmlChar * xmlUTF8Strsub(const xmlChar *utf, int start, int len) { int i; xmlChar ch; if (utf == NULL) return(NULL); if (start < 0) return(NULL); if (len < 0) return(NULL); /* * Skip over any leading chars */ for (i = 0;i < start;i++) { if ((ch=*utf++) == 0) return(NULL); if ( ch & 0x80 ) { /* if not simple ascii, verify proper format */ if ( (ch & 0xc0) != 0xc0 ) return(NULL); /* then skip over remaining bytes for this char */ while ( (ch <<= 1) & 0x80 ) if ( (*utf++ & 0xc0) != 0x80 ) return(NULL); } } return(xmlUTF8Strndup(utf, len)); } #define bottom_xmlstring #include "elfgcchack.h" xdmf-2.1.dfsg.1/Utilities/vtklibxml2/AUTHORS0000644000175000017500000000032011606020250021631 0ustar amckinstryamckinstryDaniel Veillard Bjorn Reese William Brack Igor Zlatkovic for the Windows port Aleksey Sanin xdmf-2.1.dfsg.1/Utilities/vtklibxml2/c14n.c0000644000175000017500000017676411606020250021524 0ustar amckinstryamckinstry/* * "Canonical XML" implementation * http://www.w3.org/TR/xml-c14n * * "Exclusive XML Canonicalization" implementation * http://www.w3.org/TR/xml-exc-c14n * * See Copyright for the status of this software. * * Author: Aleksey Sanin */ #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_C14N_ENABLED #ifdef LIBXML_OUTPUT_ENABLED #ifdef HAVE_STDLIB_H #include #endif #include #include #include #include #include #include #include #include /************************************************************************ * * * Some declaration better left private ATM * * * ************************************************************************/ typedef enum { XMLC14N_BEFORE_DOCUMENT_ELEMENT = 0, XMLC14N_INSIDE_DOCUMENT_ELEMENT = 1, XMLC14N_AFTER_DOCUMENT_ELEMENT = 2 } xmlC14NPosition; typedef struct _xmlC14NVisibleNsStack { int nsCurEnd; /* number of nodes in the set */ int nsPrevStart; /* the begginning of the stack for previous visible node */ int nsPrevEnd; /* the end of the stack for previous visible node */ int nsMax; /* size of the array as allocated */ xmlNsPtr *nsTab; /* array of ns in no particular order */ xmlNodePtr *nodeTab; /* array of nodes in no particular order */ } xmlC14NVisibleNsStack, *xmlC14NVisibleNsStackPtr; typedef struct _xmlC14NCtx { /* input parameters */ xmlDocPtr doc; xmlC14NIsVisibleCallback is_visible_callback; void* user_data; int with_comments; xmlOutputBufferPtr buf; /* position in the XML document */ xmlC14NPosition pos; int parent_is_doc; xmlC14NVisibleNsStackPtr ns_rendered; /* exclusive canonicalization */ int exclusive; xmlChar **inclusive_ns_prefixes; /* error number */ int error; } xmlC14NCtx, *xmlC14NCtxPtr; static xmlC14NVisibleNsStackPtr xmlC14NVisibleNsStackCreate (void); static void xmlC14NVisibleNsStackDestroy (xmlC14NVisibleNsStackPtr cur); static void xmlC14NVisibleNsStackAdd (xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlNodePtr node); static void xmlC14NVisibleNsStackSave (xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state); static void xmlC14NVisibleNsStackRestore (xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state); static void xmlC14NVisibleNsStackShift (xmlC14NVisibleNsStackPtr cur); static int xmlC14NVisibleNsStackFind (xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns); static int xmlExcC14NVisibleNsStackFind (xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlC14NCtxPtr ctx); static int xmlC14NIsNodeInNodeset (xmlNodeSetPtr nodes, xmlNodePtr node, xmlNodePtr parent); static int xmlC14NProcessNode(xmlC14NCtxPtr ctx, xmlNodePtr cur); static int xmlC14NProcessNodeList(xmlC14NCtxPtr ctx, xmlNodePtr cur); typedef enum { XMLC14N_NORMALIZE_ATTR = 0, XMLC14N_NORMALIZE_COMMENT = 1, XMLC14N_NORMALIZE_PI = 2, XMLC14N_NORMALIZE_TEXT = 3 } xmlC14NNormalizationMode; static xmlChar *xmlC11NNormalizeString(const xmlChar * input, xmlC14NNormalizationMode mode); #define xmlC11NNormalizeAttr( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_ATTR) #define xmlC11NNormalizeComment( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_COMMENT) #define xmlC11NNormalizePI( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_PI) #define xmlC11NNormalizeText( a ) \ xmlC11NNormalizeString((a), XMLC14N_NORMALIZE_TEXT) #define xmlC14NIsVisible( ctx, node, parent ) \ (((ctx)->is_visible_callback != NULL) ? \ (ctx)->is_visible_callback((ctx)->user_data, \ (xmlNodePtr)(node), (xmlNodePtr)(parent)) : 1) /************************************************************************ * * * Some factorized error routines * * * ************************************************************************/ /** * xmlC14NErrMemory: * @extra: extra informations * * Handle a redefinition of memory error */ static void xmlC14NErrMemory(const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_ERR_NO_MEMORY, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Memory allocation failed : %s\n", extra); } /** * xmlC14NErrParam: * @extra: extra informations * * Handle a redefinition of param error */ static void xmlC14NErrParam(const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_ERR_INTERNAL_ERROR, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Invalid parameter : %s\n", extra); } /** * xmlC14NErrInternal: * @extra: extra informations * * Handle a redefinition of internal error */ static void xmlC14NErrInternal(const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_ERR_INTERNAL_ERROR, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Internal error : %s\n", extra); } /** * xmlC14NErrInvalidNode: * @extra: extra informations * * Handle a redefinition of invalid node error */ static void xmlC14NErrInvalidNode(const char *node_type, const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_C14N_INVALID_NODE, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Node %s is invalid here : %s\n", node_type, extra); } /** * xmlC14NErrUnknownNode: * @extra: extra informations * * Handle a redefinition of unknown node error */ static void xmlC14NErrUnknownNode(int node_type, const char *extra) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_C14N_UNKNOW_NODE, XML_ERR_ERROR, NULL, 0, extra, NULL, NULL, 0, 0, "Unknown node type %d found : %s\n", node_type, extra); } /** * xmlC14NErrRelativeNamespace: * @extra: extra informations * * Handle a redefinition of relative namespace error */ static void xmlC14NErrRelativeNamespace(const char *ns_uri) { __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_C14N, XML_C14N_RELATIVE_NAMESPACE, XML_ERR_ERROR, NULL, 0, NULL, NULL, NULL, 0, 0, "Relative namespace UR is invalid here : %s\n", ns_uri); } /** * xmlC14NErr: * @ctxt: a C14N evaluation context * @node: the context node * @error: the erorr code * @msg: the message * @extra: extra informations * * Handle a redefinition of attribute error */ static void xmlC14NErr(xmlC14NCtxPtr ctxt, xmlNodePtr node, int error, const char * msg) { if (ctxt != NULL) ctxt->error = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_C14N, error, XML_ERR_ERROR, NULL, 0, NULL, NULL, NULL, 0, 0, msg); } /************************************************************************ * * * The implementation internals * * * ************************************************************************/ #define XML_NAMESPACES_DEFAULT 16 static int xmlC14NIsNodeInNodeset(xmlNodeSetPtr nodes, xmlNodePtr node, xmlNodePtr parent) { if((nodes != NULL) && (node != NULL)) { if(node->type != XML_NAMESPACE_DECL) { return(xmlXPathNodeSetContains(nodes, node)); } else { xmlNs ns; memcpy(&ns, node, sizeof(ns)); /* this is a libxml hack! check xpath.c for details */ if((parent != NULL) && (parent->type == XML_ATTRIBUTE_NODE)) { ns.next = (xmlNsPtr)parent->parent; } else { ns.next = (xmlNsPtr)parent; } /* * If the input is an XPath node-set, then the node-set must explicitly * contain every node to be rendered to the canonical form. */ return(xmlXPathNodeSetContains(nodes, (xmlNodePtr)&ns)); } } return(1); } static xmlC14NVisibleNsStackPtr xmlC14NVisibleNsStackCreate(void) { xmlC14NVisibleNsStackPtr ret; ret = (xmlC14NVisibleNsStackPtr) xmlMalloc(sizeof(xmlC14NVisibleNsStack)); if (ret == NULL) { xmlC14NErrMemory("creating namespaces stack"); return(NULL); } memset(ret, 0 , (size_t) sizeof(xmlC14NVisibleNsStack)); return(ret); } static void xmlC14NVisibleNsStackDestroy(xmlC14NVisibleNsStackPtr cur) { if(cur == NULL) { xmlC14NErrParam("destroying namespaces stack"); return; } if(cur->nsTab != NULL) { memset(cur->nsTab, 0, cur->nsMax * sizeof(xmlNsPtr)); xmlFree(cur->nsTab); } if(cur->nodeTab != NULL) { memset(cur->nodeTab, 0, cur->nsMax * sizeof(xmlNodePtr)); xmlFree(cur->nodeTab); } memset(cur, 0, sizeof(xmlC14NVisibleNsStack)); xmlFree(cur); } static void xmlC14NVisibleNsStackAdd(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlNodePtr node) { if((cur == NULL) || ((cur->nsTab == NULL) && (cur->nodeTab != NULL)) || ((cur->nsTab != NULL) && (cur->nodeTab == NULL))) { xmlC14NErrParam("adding namespace to stack"); return; } if ((cur->nsTab == NULL) && (cur->nodeTab == NULL)) { cur->nsTab = (xmlNsPtr*) xmlMalloc(XML_NAMESPACES_DEFAULT * sizeof(xmlNsPtr)); cur->nodeTab = (xmlNodePtr*) xmlMalloc(XML_NAMESPACES_DEFAULT * sizeof(xmlNodePtr)); if ((cur->nsTab == NULL) || (cur->nodeTab == NULL)) { xmlC14NErrMemory("adding node to stack"); return; } memset(cur->nsTab, 0 , XML_NAMESPACES_DEFAULT * sizeof(xmlNsPtr)); memset(cur->nodeTab, 0 , XML_NAMESPACES_DEFAULT * sizeof(xmlNodePtr)); cur->nsMax = XML_NAMESPACES_DEFAULT; } else if(cur->nsMax == cur->nsCurEnd) { void *tmp; int tmpSize; tmpSize = 2 * cur->nsMax; tmp = xmlRealloc(cur->nsTab, tmpSize * sizeof(xmlNsPtr)); if (tmp == NULL) { xmlC14NErrMemory("adding node to stack"); return; } cur->nsTab = (xmlNsPtr*)tmp; tmp = xmlRealloc(cur->nodeTab, tmpSize * sizeof(xmlNodePtr)); if (tmp == NULL) { xmlC14NErrMemory("adding node to stack"); return; } cur->nodeTab = (xmlNodePtr*)tmp; cur->nsMax = tmpSize; } cur->nsTab[cur->nsCurEnd] = ns; cur->nodeTab[cur->nsCurEnd] = node; ++cur->nsCurEnd; } static void xmlC14NVisibleNsStackSave(xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state) { if((cur == NULL) || (state == NULL)) { xmlC14NErrParam("saving namespaces stack"); return; } state->nsCurEnd = cur->nsCurEnd; state->nsPrevStart = cur->nsPrevStart; state->nsPrevEnd = cur->nsPrevEnd; } static void xmlC14NVisibleNsStackRestore(xmlC14NVisibleNsStackPtr cur, xmlC14NVisibleNsStackPtr state) { if((cur == NULL) || (state == NULL)) { xmlC14NErrParam("restoring namespaces stack"); return; } cur->nsCurEnd = state->nsCurEnd; cur->nsPrevStart = state->nsPrevStart; cur->nsPrevEnd = state->nsPrevEnd; } static void xmlC14NVisibleNsStackShift(xmlC14NVisibleNsStackPtr cur) { if(cur == NULL) { xmlC14NErrParam("shifting namespaces stack"); return; } cur->nsPrevStart = cur->nsPrevEnd; cur->nsPrevEnd = cur->nsCurEnd; } static int xmlC14NStrEqual(const xmlChar *str1, const xmlChar *str2) { if (str1 == str2) return(1); if (str1 == NULL) return((*str2) == '\0'); if (str2 == NULL) return((*str1) == '\0'); do { if (*str1++ != *str2) return(0); } while (*str2++); return(1); } /** * xmlC14NVisibleNsStackFind: * @ctx: the C14N context * @ns: the namespace to check * * Checks whether the given namespace was already rendered or not * * Returns 1 if we already wrote this namespace or 0 otherwise */ static int xmlC14NVisibleNsStackFind(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns) { int i; const xmlChar *prefix; const xmlChar *href; int has_empty_ns; if(cur == NULL) { xmlC14NErrParam("searching namespaces stack (c14n)"); return (0); } /* * if the default namespace xmlns="" is not defined yet then * we do not want to print it out */ prefix = ((ns == NULL) || (ns->prefix == NULL)) ? BAD_CAST "" : ns->prefix; href = ((ns == NULL) || (ns->href == NULL)) ? BAD_CAST "" : ns->href; has_empty_ns = (xmlC14NStrEqual(prefix, NULL) && xmlC14NStrEqual(href, NULL)); if (cur->nsTab != NULL) { int start = (has_empty_ns) ? 0 : cur->nsPrevStart; for (i = cur->nsCurEnd - 1; i >= start; --i) { xmlNsPtr ns1 = cur->nsTab[i]; if(xmlC14NStrEqual(prefix, (ns1 != NULL) ? ns1->prefix : NULL)) { return(xmlC14NStrEqual(href, (ns1 != NULL) ? ns1->href : NULL)); } } } return(has_empty_ns); } static int xmlExcC14NVisibleNsStackFind(xmlC14NVisibleNsStackPtr cur, xmlNsPtr ns, xmlC14NCtxPtr ctx) { int i; const xmlChar *prefix; const xmlChar *href; int has_empty_ns; if(cur == NULL) { xmlC14NErrParam("searching namespaces stack (exc c14n)"); return (0); } /* * if the default namespace xmlns="" is not defined yet then * we do not want to print it out */ prefix = ((ns == NULL) || (ns->prefix == NULL)) ? BAD_CAST "" : ns->prefix; href = ((ns == NULL) || (ns->href == NULL)) ? BAD_CAST "" : ns->href; has_empty_ns = (xmlC14NStrEqual(prefix, NULL) && xmlC14NStrEqual(href, NULL)); if (cur->nsTab != NULL) { int start = 0; for (i = cur->nsCurEnd - 1; i >= start; --i) { xmlNsPtr ns1 = cur->nsTab[i]; if(xmlC14NStrEqual(prefix, (ns1 != NULL) ? ns1->prefix : NULL)) { if(xmlC14NStrEqual(href, (ns1 != NULL) ? ns1->href : NULL)) { return(xmlC14NIsVisible(ctx, ns1, cur->nodeTab[i])); } else { return(0); } } } } return(has_empty_ns); } /** * xmlC14NIsXmlNs: * @ns: the namespace to check * * Checks whether the given namespace is a default "xml:" namespace * with href="http://www.w3.org/XML/1998/namespace" * * Returns 1 if the node is default or 0 otherwise */ /* todo: make it a define? */ static int xmlC14NIsXmlNs(xmlNsPtr ns) { return ((ns != NULL) && (xmlStrEqual(ns->prefix, BAD_CAST "xml")) && (xmlStrEqual(ns->href, BAD_CAST "http://www.w3.org/XML/1998/namespace"))); } /** * xmlC14NNsCompare: * @ns1: the pointer to first namespace * @ns2: the pointer to second namespace * * Compares the namespaces by names (prefixes). * * Returns -1 if ns1 < ns2, 0 if ns1 == ns2 or 1 if ns1 > ns2. */ static int xmlC14NNsCompare(xmlNsPtr ns1, xmlNsPtr ns2) { if (ns1 == ns2) return (0); if (ns1 == NULL) return (-1); if (ns2 == NULL) return (1); return (xmlStrcmp(ns1->prefix, ns2->prefix)); } /** * xmlC14NPrintNamespaces: * @ns: the pointer to namespace * @ctx: the C14N context * * Prints the given namespace to the output buffer from C14N context. * * Returns 1 on success or 0 on fail. */ static int xmlC14NPrintNamespaces(const xmlNsPtr ns, xmlC14NCtxPtr ctx) { if ((ns == NULL) || (ctx == NULL)) { xmlC14NErrParam("writing namespaces"); return 0; } if (ns->prefix != NULL) { xmlOutputBufferWriteString(ctx->buf, " xmlns:"); xmlOutputBufferWriteString(ctx->buf, (const char *) ns->prefix); xmlOutputBufferWriteString(ctx->buf, "=\""); } else { xmlOutputBufferWriteString(ctx->buf, " xmlns=\""); } if(ns->href != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) ns->href); } xmlOutputBufferWriteString(ctx->buf, "\""); return (1); } /** * xmlC14NProcessNamespacesAxis: * @ctx: the C14N context * @node: the current node * * Prints out canonical namespace axis of the current node to the * buffer from C14N context as follows * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Namespace Axis * Consider a list L containing only namespace nodes in the * axis and in the node-set in lexicographic order (ascending). To begin * processing L, if the first node is not the default namespace node (a node * with no namespace URI and no local name), then generate a space followed * by xmlns="" if and only if the following conditions are met: * - the element E that owns the axis is in the node-set * - The nearest ancestor element of E in the node-set has a default * namespace node in the node-set (default namespace nodes always * have non-empty values in XPath) * The latter condition eliminates unnecessary occurrences of xmlns="" in * the canonical form since an element only receives an xmlns="" if its * default namespace is empty and if it has an immediate parent in the * canonical form that has a non-empty default namespace. To finish * processing L, simply process every namespace node in L, except omit * namespace node with local name xml, which defines the xml prefix, * if its string value is http://www.w3.org/XML/1998/namespace. * * Exclusive XML Canonicalization v 1.0 (http://www.w3.org/TR/xml-exc-c14n) * Canonical XML applied to a document subset requires the search of the * ancestor nodes of each orphan element node for attributes in the xml * namespace, such as xml:lang and xml:space. These are copied into the * element node except if a declaration of the same attribute is already * in the attribute axis of the element (whether or not it is included in * the document subset). This search and copying are omitted from the * Exclusive XML Canonicalization method. * * Returns 0 on success or -1 on fail. */ static int xmlC14NProcessNamespacesAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible) { xmlNodePtr n; xmlNsPtr ns, tmp; xmlListPtr list; int already_rendered; int has_empty_ns = 0; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing namespaces axis (c14n)"); return (-1); } /* * Create a sorted list to store element namespaces */ list = xmlListCreate(NULL, (xmlListDataCompare) xmlC14NNsCompare); if (list == NULL) { xmlC14NErrInternal("creating namespaces list (c14n)"); return (-1); } /* check all namespaces */ for(n = cur; n != NULL; n = n->parent) { for(ns = n->nsDef; ns != NULL; ns = ns->next) { tmp = xmlSearchNs(cur->doc, cur, ns->prefix); if((tmp == ns) && !xmlC14NIsXmlNs(ns) && xmlC14NIsVisible(ctx, ns, cur)) { already_rendered = xmlC14NVisibleNsStackFind(ctx->ns_rendered, ns); if(visible) { xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur); } if(!already_rendered) { xmlListInsert(list, ns); } if(xmlStrlen(ns->prefix) == 0) { has_empty_ns = 1; } } } } /** * if the first node is not the default namespace node (a node with no * namespace URI and no local name), then generate a space followed by * xmlns="" if and only if the following conditions are met: * - the element E that owns the axis is in the node-set * - the nearest ancestor element of E in the node-set has a default * namespace node in the node-set (default namespace nodes always * have non-empty values in XPath) */ if(visible && !has_empty_ns) { static xmlNs ns_default; memset(&ns_default, 0, sizeof(ns_default)); if(!xmlC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default)) { xmlC14NPrintNamespaces(&ns_default, ctx); } } /* * print out all elements from list */ xmlListWalk(list, (xmlListWalker) xmlC14NPrintNamespaces, (const void *) ctx); /* * Cleanup */ xmlListDelete(list); return (0); } /** * xmlExcC14NProcessNamespacesAxis: * @ctx: the C14N context * @node: the current node * * Prints out exclusive canonical namespace axis of the current node to the * buffer from C14N context as follows * * Exclusive XML Canonicalization * http://www.w3.org/TR/xml-exc-c14n * * If the element node is in the XPath subset then output the node in * accordance with Canonical XML except for namespace nodes which are * rendered as follows: * * 1. Render each namespace node iff: * * it is visibly utilized by the immediate parent element or one of * its attributes, or is present in InclusiveNamespaces PrefixList, and * * its prefix and value do not appear in ns_rendered. ns_rendered is * obtained by popping the state stack in order to obtain a list of * prefixes and their values which have already been rendered by * an output ancestor of the namespace node's parent element. * 2. Append the rendered namespace node to the list ns_rendered of namespace * nodes rendered by output ancestors. Push ns_rendered on state stack and * recurse. * 3. After the recursion returns, pop thestate stack. * * * Returns 0 on success or -1 on fail. */ static int xmlExcC14NProcessNamespacesAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible) { xmlNsPtr ns; xmlListPtr list; xmlAttrPtr attr; int already_rendered; int has_empty_ns = 0; int has_visibly_utilized_empty_ns = 0; int has_empty_ns_in_inclusive_list = 0; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing namespaces axis (exc c14n)"); return (-1); } if(!ctx->exclusive) { xmlC14NErrParam("processing namespaces axis (exc c14n)"); return (-1); } /* * Create a sorted list to store element namespaces */ list = xmlListCreate(NULL, (xmlListDataCompare) xmlC14NNsCompare); if (list == NULL) { xmlC14NErrInternal("creating namespaces list (exc c14n)"); return (-1); } /* * process inclusive namespaces: * All namespace nodes appearing on inclusive ns list are * handled as provided in Canonical XML */ if(ctx->inclusive_ns_prefixes != NULL) { xmlChar *prefix; int i; for (i = 0; ctx->inclusive_ns_prefixes[i] != NULL; ++i) { prefix = ctx->inclusive_ns_prefixes[i]; /* * Special values for namespace with empty prefix */ if (xmlStrEqual(prefix, BAD_CAST "#default") || xmlStrEqual(prefix, BAD_CAST "")) { prefix = NULL; has_empty_ns_in_inclusive_list = 1; } ns = xmlSearchNs(cur->doc, cur, prefix); if((ns != NULL) && !xmlC14NIsXmlNs(ns) && xmlC14NIsVisible(ctx, ns, cur)) { already_rendered = xmlC14NVisibleNsStackFind(ctx->ns_rendered, ns); if(visible) { xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur); } if(!already_rendered) { xmlListInsert(list, ns); } if(xmlStrlen(ns->prefix) == 0) { has_empty_ns = 1; } } } } /* add node namespace */ if(cur->ns != NULL) { ns = cur->ns; } else { ns = xmlSearchNs(cur->doc, cur, NULL); has_visibly_utilized_empty_ns = 1; } if((ns != NULL) && !xmlC14NIsXmlNs(ns)) { if(visible && xmlC14NIsVisible(ctx, ns, cur)) { if(!xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, ns, ctx)) { xmlListInsert(list, ns); } } if(visible) { xmlC14NVisibleNsStackAdd(ctx->ns_rendered, ns, cur); } if(xmlStrlen(ns->prefix) == 0) { has_empty_ns = 1; } } /* add attributes */ for(attr = cur->properties; attr != NULL; attr = attr->next) { /* * we need to check that attribute is visible and has non * default namespace (XML Namespaces: "default namespaces * do not apply directly to attributes") */ if((attr->ns != NULL) && !xmlC14NIsXmlNs(attr->ns) && xmlC14NIsVisible(ctx, attr, cur)) { already_rendered = xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, attr->ns, ctx); xmlC14NVisibleNsStackAdd(ctx->ns_rendered, attr->ns, cur); if(!already_rendered && visible) { xmlListInsert(list, attr->ns); } if(xmlStrlen(attr->ns->prefix) == 0) { has_empty_ns = 1; } } else if((attr->ns != NULL) && (xmlStrlen(attr->ns->prefix) == 0) && (xmlStrlen(attr->ns->href) == 0)) { has_visibly_utilized_empty_ns = 1; } } /* * Process xmlns="" */ if(visible && has_visibly_utilized_empty_ns && !has_empty_ns && !has_empty_ns_in_inclusive_list) { static xmlNs ns_default; memset(&ns_default, 0, sizeof(ns_default)); already_rendered = xmlExcC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default, ctx); if(!already_rendered) { xmlC14NPrintNamespaces(&ns_default, ctx); } } else if(visible && !has_empty_ns && has_empty_ns_in_inclusive_list) { static xmlNs ns_default; memset(&ns_default, 0, sizeof(ns_default)); if(!xmlC14NVisibleNsStackFind(ctx->ns_rendered, &ns_default)) { xmlC14NPrintNamespaces(&ns_default, ctx); } } /* * print out all elements from list */ xmlListWalk(list, (xmlListWalker) xmlC14NPrintNamespaces, (const void *) ctx); /* * Cleanup */ xmlListDelete(list); return (0); } /** * xmlC14NAttrsCompare: * @attr1: the pointer tls o first attr * @attr2: the pointer to second attr * * Prints the given attribute to the output buffer from C14N context. * * Returns -1 if attr1 < attr2, 0 if attr1 == attr2 or 1 if attr1 > attr2. */ static int xmlC14NAttrsCompare(xmlAttrPtr attr1, xmlAttrPtr attr2) { int ret = 0; /* * Simple cases */ if (attr1 == attr2) return (0); if (attr1 == NULL) return (-1); if (attr2 == NULL) return (1); if (attr1->ns == attr2->ns) { return (xmlStrcmp(attr1->name, attr2->name)); } /* * Attributes in the default namespace are first * because the default namespace is not applied to * unqualified attributes */ if (attr1->ns == NULL) return (-1); if (attr2->ns == NULL) return (1); if (attr1->ns->prefix == NULL) return (-1); if (attr2->ns->prefix == NULL) return (1); ret = xmlStrcmp(attr1->ns->href, attr2->ns->href); if (ret == 0) { ret = xmlStrcmp(attr1->name, attr2->name); } return (ret); } /** * xmlC14NPrintAttrs: * @attr: the pointer to attr * @ctx: the C14N context * * Prints out canonical attribute urrent node to the * buffer from C14N context as follows * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Returns 1 on success or 0 on fail. */ static int xmlC14NPrintAttrs(const xmlAttrPtr attr, xmlC14NCtxPtr ctx) { xmlChar *value; xmlChar *buffer; if ((attr == NULL) || (ctx == NULL)) { xmlC14NErrParam("writing attributes"); return (0); } xmlOutputBufferWriteString(ctx->buf, " "); if (attr->ns != NULL && xmlStrlen(attr->ns->prefix) > 0) { xmlOutputBufferWriteString(ctx->buf, (const char *) attr->ns->prefix); xmlOutputBufferWriteString(ctx->buf, ":"); } xmlOutputBufferWriteString(ctx->buf, (const char *) attr->name); xmlOutputBufferWriteString(ctx->buf, "=\""); value = xmlNodeListGetString(attr->doc, attr->children, 1); /* todo: should we log an error if value==NULL ? */ if (value != NULL) { buffer = xmlC11NNormalizeAttr(value); xmlFree(value); if (buffer != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) buffer); xmlFree(buffer); } else { xmlC14NErrInternal("normalizing attributes axis"); return (0); } } xmlOutputBufferWriteString(ctx->buf, "\""); return (1); } /** * xmlC14NProcessAttrsAxis: * @ctx: the C14N context * @cur: the current node * @parent_visible: the visibility of parent node * * Prints out canonical attribute axis of the current node to the * buffer from C14N context as follows * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Attribute Axis * In lexicographic order (ascending), process each node that * is in the element's attribute axis and in the node-set. * * The processing of an element node E MUST be modified slightly * when an XPath node-set is given as input and the element's * parent is omitted from the node-set. * * * Exclusive XML Canonicalization v 1.0 (http://www.w3.org/TR/xml-exc-c14n) * * Canonical XML applied to a document subset requires the search of the * ancestor nodes of each orphan element node for attributes in the xml * namespace, such as xml:lang and xml:space. These are copied into the * element node except if a declaration of the same attribute is already * in the attribute axis of the element (whether or not it is included in * the document subset). This search and copying are omitted from the * Exclusive XML Canonicalization method. * * Returns 0 on success or -1 on fail. */ static int xmlC14NProcessAttrsAxis(xmlC14NCtxPtr ctx, xmlNodePtr cur, int parent_visible) { xmlAttrPtr attr; xmlListPtr list; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing attributes axis"); return (-1); } /* * Create a sorted list to store element attributes */ list = xmlListCreate(NULL, (xmlListDataCompare) xmlC14NAttrsCompare); if (list == NULL) { xmlC14NErrInternal("creating attributes list"); return (-1); } /* * Add all visible attributes from current node. */ attr = cur->properties; while (attr != NULL) { /* check that attribute is visible */ if (xmlC14NIsVisible(ctx, attr, cur)) { xmlListInsert(list, attr); } attr = attr->next; } /* * include attributes in "xml" namespace defined in ancestors * (only for non-exclusive XML Canonicalization) */ if (parent_visible && (!ctx->exclusive) && (cur->parent != NULL) && (!xmlC14NIsVisible(ctx, cur->parent, cur->parent->parent))) { /* * If XPath node-set is not specified then the parent is always * visible! */ cur = cur->parent; while (cur != NULL) { attr = cur->properties; while (attr != NULL) { if ((attr->ns != NULL) && (xmlStrEqual(attr->ns->prefix, BAD_CAST "xml"))) { if (xmlListSearch(list, attr) == NULL) { xmlListInsert(list, attr); } } attr = attr->next; } cur = cur->parent; } } /* * print out all elements from list */ xmlListWalk(list, (xmlListWalker) xmlC14NPrintAttrs, (const void *) ctx); /* * Cleanup */ xmlListDelete(list); return (0); } /** * xmlC14NCheckForRelativeNamespaces: * @ctx: the C14N context * @cur: the current element node * * Checks that current element node has no relative namespaces defined * * Returns 0 if the node has no relative namespaces or -1 otherwise. */ static int xmlC14NCheckForRelativeNamespaces(xmlC14NCtxPtr ctx, xmlNodePtr cur) { xmlNsPtr ns; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("checking for relative namespaces"); return (-1); } ns = cur->nsDef; while (ns != NULL) { if (xmlStrlen(ns->href) > 0) { xmlURIPtr uri; uri = xmlParseURI((const char *) ns->href); if (uri == NULL) { xmlC14NErrInternal("parsing namespace uri"); return (-1); } if (xmlStrlen((const xmlChar *) uri->scheme) == 0) { xmlC14NErrRelativeNamespace(uri->scheme); xmlFreeURI(uri); return (-1); } if ((xmlStrcasecmp((const xmlChar *) uri->scheme, BAD_CAST "urn") != 0) && (xmlStrcasecmp((const xmlChar *) uri->scheme, BAD_CAST "dav") !=0) && (xmlStrlen((const xmlChar *) uri->server) == 0)) { xmlC14NErrRelativeNamespace(uri->scheme); xmlFreeURI(uri); return (-1); } xmlFreeURI(uri); } ns = ns->next; } return (0); } /** * xmlC14NProcessElementNode: * @ctx: the pointer to C14N context object * @cur: the node to process * * Canonical XML v 1.0 (http://www.w3.org/TR/xml-c14n) * * Element Nodes * If the element is not in the node-set, then the result is obtained * by processing the namespace axis, then the attribute axis, then * processing the child nodes of the element that are in the node-set * (in document order). If the element is in the node-set, then the result * is an open angle bracket (<), the element QName, the result of * processing the namespace axis, the result of processing the attribute * axis, a close angle bracket (>), the result of processing the child * nodes of the element that are in the node-set (in document order), an * open angle bracket, a forward slash (/), the element QName, and a close * angle bracket. * * Returns non-negative value on success or negative value on fail */ static int xmlC14NProcessElementNode(xmlC14NCtxPtr ctx, xmlNodePtr cur, int visible) { int ret; xmlC14NVisibleNsStack state; int parent_is_doc = 0; if ((ctx == NULL) || (cur == NULL) || (cur->type != XML_ELEMENT_NODE)) { xmlC14NErrParam("processing element node"); return (-1); } /* * Check relative relative namespaces: * implementations of XML canonicalization MUST report an operation * failure on documents containing relative namespace URIs. */ if (xmlC14NCheckForRelativeNamespaces(ctx, cur) < 0) { xmlC14NErrInternal("checking for relative namespaces"); return (-1); } /* * Save ns_rendered stack position */ memset(&state, 0, sizeof(state)); xmlC14NVisibleNsStackSave(ctx->ns_rendered, &state); if (visible) { if (ctx->parent_is_doc) { /* save this flag into the stack */ parent_is_doc = ctx->parent_is_doc; ctx->parent_is_doc = 0; ctx->pos = XMLC14N_INSIDE_DOCUMENT_ELEMENT; } xmlOutputBufferWriteString(ctx->buf, "<"); if ((cur->ns != NULL) && (xmlStrlen(cur->ns->prefix) > 0)) { xmlOutputBufferWriteString(ctx->buf, (const char *) cur->ns->prefix); xmlOutputBufferWriteString(ctx->buf, ":"); } xmlOutputBufferWriteString(ctx->buf, (const char *) cur->name); } if (!ctx->exclusive) { ret = xmlC14NProcessNamespacesAxis(ctx, cur, visible); } else { ret = xmlExcC14NProcessNamespacesAxis(ctx, cur, visible); } if (ret < 0) { xmlC14NErrInternal("processing namespaces axis"); return (-1); } /* todo: shouldn't this go to "visible only"? */ if(visible) { xmlC14NVisibleNsStackShift(ctx->ns_rendered); } ret = xmlC14NProcessAttrsAxis(ctx, cur, visible); if (ret < 0) { xmlC14NErrInternal("processing attributes axis"); return (-1); } if (visible) { xmlOutputBufferWriteString(ctx->buf, ">"); } if (cur->children != NULL) { ret = xmlC14NProcessNodeList(ctx, cur->children); if (ret < 0) { xmlC14NErrInternal("processing childrens list"); return (-1); } } if (visible) { xmlOutputBufferWriteString(ctx->buf, "ns != NULL) && (xmlStrlen(cur->ns->prefix) > 0)) { xmlOutputBufferWriteString(ctx->buf, (const char *) cur->ns->prefix); xmlOutputBufferWriteString(ctx->buf, ":"); } xmlOutputBufferWriteString(ctx->buf, (const char *) cur->name); xmlOutputBufferWriteString(ctx->buf, ">"); if (parent_is_doc) { /* restore this flag from the stack for next node */ ctx->parent_is_doc = parent_is_doc; ctx->pos = XMLC14N_AFTER_DOCUMENT_ELEMENT; } } /* * Restore ns_rendered stack position */ xmlC14NVisibleNsStackRestore(ctx->ns_rendered, &state); return (0); } /** * xmlC14NProcessNode: * @ctx: the pointer to C14N context object * @cur: the node to process * * Processes the given node * * Returns non-negative value on success or negative value on fail */ static int xmlC14NProcessNode(xmlC14NCtxPtr ctx, xmlNodePtr cur) { int ret = 0; int visible; if ((ctx == NULL) || (cur == NULL)) { xmlC14NErrParam("processing node"); return (-1); } visible = xmlC14NIsVisible(ctx, cur, cur->parent); switch (cur->type) { case XML_ELEMENT_NODE: ret = xmlC14NProcessElementNode(ctx, cur, visible); break; case XML_CDATA_SECTION_NODE: case XML_TEXT_NODE: /* * Text Nodes * the string value, except all ampersands are replaced * by &, all open angle brackets (<) are replaced by <, all closing * angle brackets (>) are replaced by >, and all #xD characters are * replaced by . */ /* cdata sections are processed as text nodes */ /* todo: verify that cdata sections are included in XPath nodes set */ if ((visible) && (cur->content != NULL)) { xmlChar *buffer; buffer = xmlC11NNormalizeText(cur->content); if (buffer != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) buffer); xmlFree(buffer); } else { xmlC14NErrInternal("normalizing text node"); return (-1); } } break; case XML_PI_NODE: /* * Processing Instruction (PI) Nodes- * The opening PI symbol (). If the string value is empty, * then the leading space is not added. Also, a trailing #xA is * rendered after the closing PI symbol for PI children of the * root node with a lesser document order than the document * element, and a leading #xA is rendered before the opening PI * symbol of PI children of the root node with a greater document * order than the document element. */ if (visible) { if (ctx->pos == XMLC14N_AFTER_DOCUMENT_ELEMENT) { xmlOutputBufferWriteString(ctx->buf, "\x0Abuf, "buf, (const char *) cur->name); if ((cur->content != NULL) && (*(cur->content) != '\0')) { xmlChar *buffer; xmlOutputBufferWriteString(ctx->buf, " "); /* todo: do we need to normalize pi? */ buffer = xmlC11NNormalizePI(cur->content); if (buffer != NULL) { xmlOutputBufferWriteString(ctx->buf, (const char *) buffer); xmlFree(buffer); } else { xmlC14NErrInternal("normalizing pi node"); return (-1); } } if (ctx->pos == XMLC14N_BEFORE_DOCUMENT_ELEMENT) { xmlOutputBufferWriteString(ctx->buf, "?>\x0A"); } else { xmlOutputBufferWriteString(ctx->buf, "?>"); } } break; case XML_COMMENT_NODE: /* * Comment Nodes * Nothing if generating canonical XML without comments. For * canonical XML with comments, generate the opening comment * symbol (). Also, a trailing #xA is rendered * after the closing comment symbol for comment children of the * root node with a lesser document order than the document * element, and a leading #xA is rendered before the opening * comment symbol of comment children of the root node with a * greater document order than the document element. (Comment * children of the root node represent comments outside of the * top-level document element and outside of the document type * declaration). */ if (visible && ctx->with_comments) { if (ctx->pos == XMLC14N_AFTER_DOCUMENT_ELEMENT) { xmlOutputBufferWriteString(ctx->buf, "\x0A\x0A"); } else { xmlOutputBufferWriteString(ctx->buf, "-->"); } } break; case XML_DOCUMENT_NODE: case XML_DOCUMENT_FRAG_NODE: /* should be processed as document? */ #ifdef LIBXML_DOCB_ENABLED case XML_DOCB_DOCUMENT_NODE: /* should be processed as document? */ #endif #ifdef LIBXML_HTML_ENABLED case XML_HTML_DOCUMENT_NODE: /* should be processed as document? */ #endif if (cur->children != NULL) { ctx->pos = XMLC14N_BEFORE_DOCUMENT_ELEMENT; ctx->parent_is_doc = 1; ret = xmlC14NProcessNodeList(ctx, cur->children); } break; case XML_ATTRIBUTE_NODE: xmlC14NErrInvalidNode("XML_ATTRIBUTE_NODE", "processing node"); return (-1); case XML_NAMESPACE_DECL: xmlC14NErrInvalidNode("XML_NAMESPACE_DECL", "processing node"); return (-1); case XML_ENTITY_REF_NODE: xmlC14NErrInvalidNode("XML_ENTITY_REF_NODE", "processing node"); return (-1); case XML_ENTITY_NODE: xmlC14NErrInvalidNode("XML_ENTITY_NODE", "processing node"); return (-1); case XML_DOCUMENT_TYPE_NODE: case XML_NOTATION_NODE: case XML_DTD_NODE: case XML_ELEMENT_DECL: case XML_ATTRIBUTE_DECL: case XML_ENTITY_DECL: #ifdef LIBXML_XINCLUDE_ENABLED case XML_XINCLUDE_START: case XML_XINCLUDE_END: #endif /* * should be ignored according to "W3C Canonical XML" */ break; default: xmlC14NErrUnknownNode(cur->type, "processing node"); return (-1); } return (ret); } /** * xmlC14NProcessNodeList: * @ctx: the pointer to C14N context object * @cur: the node to start from * * Processes all nodes in the row starting from cur. * * Returns non-negative value on success or negative value on fail */ static int xmlC14NProcessNodeList(xmlC14NCtxPtr ctx, xmlNodePtr cur) { int ret; if (ctx == NULL) { xmlC14NErrParam("processing node list"); return (-1); } for (ret = 0; cur != NULL && ret >= 0; cur = cur->next) { ret = xmlC14NProcessNode(ctx, cur); } return (ret); } /** * xmlC14NFreeCtx: * @ctx: the pointer to C14N context object * * Cleanups the C14N context object. */ static void xmlC14NFreeCtx(xmlC14NCtxPtr ctx) { if (ctx == NULL) { xmlC14NErrParam("freeing context"); return; } if (ctx->ns_rendered != NULL) { xmlC14NVisibleNsStackDestroy(ctx->ns_rendered); } xmlFree(ctx); } /** * xmlC14NNewCtx: * @doc: the XML document for canonization * @is_visible_callback:the function to use to determine is node visible * or not * @user_data: the first parameter for @is_visible_callback function * (in most cases, it is nodes set) * @inclusive_ns_prefixe the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization) * @with_comments: include comments in the result (!=0) or not (==0) * @buf: the output buffer to store canonical XML; this * buffer MUST have encoder==NULL because C14N requires * UTF-8 output * * Creates new C14N context object to store C14N parameters. * * Returns pointer to newly created object (success) or NULL (fail) */ static xmlC14NCtxPtr xmlC14NNewCtx(xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback, void* user_data, int exclusive, xmlChar ** inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf) { xmlC14NCtxPtr ctx = NULL; if ((doc == NULL) || (buf == NULL)) { xmlC14NErrParam("creating new context"); return (NULL); } /* * Validate the encoding output buffer encoding */ if (buf->encoder != NULL) { xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8, "xmlC14NNewCtx: output buffer encoder != NULL but C14N requires UTF8 output\n"); return (NULL); } /* * Validate the XML document encoding value, if provided. */ if (doc->charset != XML_CHAR_ENCODING_UTF8) { xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8, "xmlC14NNewCtx: source document not in UTF8\n"); return (NULL); } /* * Allocate a new xmlC14NCtxPtr and fill the fields. */ ctx = (xmlC14NCtxPtr) xmlMalloc(sizeof(xmlC14NCtx)); if (ctx == NULL) { xmlC14NErrMemory("creating context"); return (NULL); } memset(ctx, 0, sizeof(xmlC14NCtx)); /* * initialize C14N context */ ctx->doc = doc; ctx->with_comments = with_comments; ctx->is_visible_callback = is_visible_callback; ctx->user_data = user_data; ctx->buf = buf; ctx->parent_is_doc = 1; ctx->pos = XMLC14N_BEFORE_DOCUMENT_ELEMENT; ctx->ns_rendered = xmlC14NVisibleNsStackCreate(); if(ctx->ns_rendered == NULL) { xmlC14NErr(ctx, (xmlNodePtr) doc, XML_C14N_CREATE_STACK, "xmlC14NNewCtx: xmlC14NVisibleNsStackCreate failed\n"); xmlC14NFreeCtx(ctx); return (NULL); } /* * Set "exclusive" flag, create a nodes set for namespaces * stack and remember list of incluseve prefixes */ if (exclusive) { ctx->exclusive = 1; ctx->inclusive_ns_prefixes = inclusive_ns_prefixes; } return (ctx); } /** * xmlC14NExecute: * @doc: the XML document for canonization * @is_visible_callback:the function to use to determine is node visible * or not * @user_data: the first parameter for @is_visible_callback function * (in most cases, it is nodes set) * @exclusive: the exclusive flag (0 - non-exclusive canonicalization; * otherwise - exclusive canonicalization) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @buf: the output buffer to store canonical XML; this * buffer MUST have encoder==NULL because C14N requires * UTF-8 output * * Dumps the canonized image of given XML document into the provided buffer. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns non-negative value on success or a negative value on fail */ int xmlC14NExecute(xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback, void* user_data, int exclusive, xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf) { xmlC14NCtxPtr ctx; int ret; if ((buf == NULL) || (doc == NULL)) { xmlC14NErrParam("executing c14n"); return (-1); } /* * Validate the encoding output buffer encoding */ if (buf->encoder != NULL) { xmlC14NErr(NULL, (xmlNodePtr) doc, XML_C14N_REQUIRES_UTF8, "xmlC14NExecute: output buffer encoder != NULL but C14N requires UTF8 output\n"); return (-1); } ctx = xmlC14NNewCtx(doc, is_visible_callback, user_data, exclusive, inclusive_ns_prefixes, with_comments, buf); if (ctx == NULL) { xmlC14NErr(NULL, (xmlNodePtr) doc, XML_C14N_CREATE_CTXT, "xmlC14NExecute: unable to create C14N context\n"); return (-1); } /* * Root Node * The root node is the parent of the top-level document element. The * result of processing each of its child nodes that is in the node-set * in document order. The root node does not generate a byte order mark, * XML declaration, nor anything from within the document type * declaration. */ if (doc->children != NULL) { ret = xmlC14NProcessNodeList(ctx, doc->children); if (ret < 0) { xmlC14NErrInternal("processing docs children list"); xmlC14NFreeCtx(ctx); return (-1); } } /* * Flush buffer to get number of bytes written */ ret = xmlOutputBufferFlush(buf); if (ret < 0) { xmlC14NErrInternal("flushing output buffer"); xmlC14NFreeCtx(ctx); return (-1); } /* * Cleanup */ xmlC14NFreeCtx(ctx); return (ret); } /** * xmlC14NDocSaveTo: * @doc: the XML document for canonization * @nodes: the nodes set to be included in the canonized image * or NULL if all document nodes should be included * @exclusive: the exclusive flag (0 - non-exclusive canonicalization; * otherwise - exclusive canonicalization) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @buf: the output buffer to store canonical XML; this * buffer MUST have encoder==NULL because C14N requires * UTF-8 output * * Dumps the canonized image of given XML document into the provided buffer. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns non-negative value on success or a negative value on fail */ int xmlC14NDocSaveTo(xmlDocPtr doc, xmlNodeSetPtr nodes, int exclusive, xmlChar ** inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf) { return(xmlC14NExecute(doc, (xmlC14NIsVisibleCallback)xmlC14NIsNodeInNodeset, nodes, exclusive, inclusive_ns_prefixes, with_comments, buf)); } /** * xmlC14NDocDumpMemory: * @doc: the XML document for canonization * @nodes: the nodes set to be included in the canonized image * or NULL if all document nodes should be included * @exclusive: the exclusive flag (0 - non-exclusive canonicalization; * otherwise - exclusive canonicalization) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @doc_txt_ptr: the memory pointer for allocated canonical XML text; * the caller of this functions is responsible for calling * xmlFree() to free allocated memory * * Dumps the canonized image of given XML document into memory. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns the number of bytes written on success or a negative value on fail */ int xmlC14NDocDumpMemory(xmlDocPtr doc, xmlNodeSetPtr nodes, int exclusive, xmlChar ** inclusive_ns_prefixes, int with_comments, xmlChar ** doc_txt_ptr) { int ret; xmlOutputBufferPtr buf; if (doc_txt_ptr == NULL) { xmlC14NErrParam("dumping doc to memory"); return (-1); } *doc_txt_ptr = NULL; /* * create memory buffer with UTF8 (default) encoding */ buf = xmlAllocOutputBuffer(NULL); if (buf == NULL) { xmlC14NErrMemory("creating output buffer"); return (-1); } /* * canonize document and write to buffer */ ret = xmlC14NDocSaveTo(doc, nodes, exclusive, inclusive_ns_prefixes, with_comments, buf); if (ret < 0) { xmlC14NErrInternal("saving doc to output buffer"); (void) xmlOutputBufferClose(buf); return (-1); } ret = buf->buffer->use; if (ret > 0) { *doc_txt_ptr = xmlStrndup(buf->buffer->content, ret); } (void) xmlOutputBufferClose(buf); if ((*doc_txt_ptr == NULL) && (ret > 0)) { xmlC14NErrMemory("coping canonicanized document"); return (-1); } return (ret); } /** * xmlC14NDocSave: * @doc: the XML document for canonization * @nodes: the nodes set to be included in the canonized image * or NULL if all document nodes should be included * @exclusive: the exclusive flag (0 - non-exclusive canonicalization; * otherwise - exclusive canonicalization) * @inclusive_ns_prefixes: the list of inclusive namespace prefixes * ended with a NULL or NULL if there is no * inclusive namespaces (only for exclusive * canonicalization, ignored otherwise) * @with_comments: include comments in the result (!=0) or not (==0) * @filename: the filename to store canonical XML image * @compression: the compression level (zlib requred): * -1 - libxml default, * 0 - uncompressed, * >0 - compression level * * Dumps the canonized image of given XML document into the file. * For details see "Canonical XML" (http://www.w3.org/TR/xml-c14n) or * "Exclusive XML Canonicalization" (http://www.w3.org/TR/xml-exc-c14n) * * Returns the number of bytes written success or a negative value on fail */ int xmlC14NDocSave(xmlDocPtr doc, xmlNodeSetPtr nodes, int exclusive, xmlChar ** inclusive_ns_prefixes, int with_comments, const char *filename, int compression) { xmlOutputBufferPtr buf; int ret; if (filename == NULL) { xmlC14NErrParam("saving doc"); return (-1); } #ifdef HAVE_ZLIB_H if (compression < 0) compression = xmlGetCompressMode(); #endif /* * save the content to a temp buffer, use default UTF8 encoding. */ buf = xmlOutputBufferCreateFilename(filename, NULL, compression); if (buf == NULL) { xmlC14NErrInternal("creating temporary filename"); return (-1); } /* * canonize document and write to buffer */ ret = xmlC14NDocSaveTo(doc, nodes, exclusive, inclusive_ns_prefixes, with_comments, buf); if (ret < 0) { xmlC14NErrInternal("cannicanize document to buffer"); (void) xmlOutputBufferClose(buf); return (-1); } /* * get the numbers of bytes written */ ret = xmlOutputBufferClose(buf); return (ret); } /* * Macro used to grow the current buffer. */ #define growBufferReentrant() { \ buffer_size *= 2; \ buffer = (xmlChar *) \ xmlRealloc(buffer, buffer_size * sizeof(xmlChar)); \ if (buffer == NULL) { \ xmlC14NErrMemory("growing buffer"); \ return(NULL); \ } \ } /** * xmlC11NNormalizeString: * @input: the input string * @mode: the normalization mode (attribute, comment, PI or text) * * Converts a string to a canonical (normalized) format. The code is stolen * from xmlEncodeEntitiesReentrant(). Added normalization of \x09, \x0a, \x0A * and the @mode parameter * * Returns a normalized string (caller is responsible for calling xmlFree()) * or NULL if an error occurs */ static xmlChar * xmlC11NNormalizeString(const xmlChar * input, xmlC14NNormalizationMode mode) { const xmlChar *cur = input; xmlChar *buffer = NULL; xmlChar *out = NULL; int buffer_size = 0; if (input == NULL) return (NULL); /* * allocate an translation buffer. */ buffer_size = 1000; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) { xmlC14NErrMemory("allocating buffer"); return (NULL); } out = buffer; while (*cur != '\0') { if ((out - buffer) > (buffer_size - 10)) { int indx = out - buffer; growBufferReentrant(); out = &buffer[indx]; } if ((*cur == '<') && ((mode == XMLC14N_NORMALIZE_ATTR) || (mode == XMLC14N_NORMALIZE_TEXT))) { *out++ = '&'; *out++ = 'l'; *out++ = 't'; *out++ = ';'; } else if ((*cur == '>') && (mode == XMLC14N_NORMALIZE_TEXT)) { *out++ = '&'; *out++ = 'g'; *out++ = 't'; *out++ = ';'; } else if ((*cur == '&') && ((mode == XMLC14N_NORMALIZE_ATTR) || (mode == XMLC14N_NORMALIZE_TEXT))) { *out++ = '&'; *out++ = 'a'; *out++ = 'm'; *out++ = 'p'; *out++ = ';'; } else if ((*cur == '"') && (mode == XMLC14N_NORMALIZE_ATTR)) { *out++ = '&'; *out++ = 'q'; *out++ = 'u'; *out++ = 'o'; *out++ = 't'; *out++ = ';'; } else if ((*cur == '\x09') && (mode == XMLC14N_NORMALIZE_ATTR)) { *out++ = '&'; *out++ = '#'; *out++ = 'x'; *out++ = '9'; *out++ = ';'; } else if ((*cur == '\x0A') && (mode == XMLC14N_NORMALIZE_ATTR)) { *out++ = '&'; *out++ = '#'; *out++ = 'x'; *out++ = 'A'; *out++ = ';'; } else if ((*cur == '\x0D') && ((mode == XMLC14N_NORMALIZE_ATTR) || (mode == XMLC14N_NORMALIZE_TEXT) || (mode == XMLC14N_NORMALIZE_COMMENT) || (mode == XMLC14N_NORMALIZE_PI))) { *out++ = '&'; *out++ = '#'; *out++ = 'x'; *out++ = 'D'; *out++ = ';'; } else { /* * Works because on UTF-8, all extended sequences cannot * result in bytes in the ASCII range. */ *out++ = *cur; } cur++; } *out++ = 0; return (buffer); } #endif /* LIBXML_OUTPUT_ENABLED */ #define bottom_c14n #include "elfgcchack.h" #endif /* LIBXML_C14N_ENABLED */ xdmf-2.1.dfsg.1/Utilities/vtklibxml2/HTMLtree.c0000644000175000017500000010644311606020250022366 0ustar amckinstryamckinstry/* * HTMLtree.c : implementation of access function for an HTML tree. * * See Copyright for the status of this software. * * daniel@veillard.com */ #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_HTML_ENABLED #include /* for memset() only ! */ #ifdef HAVE_CTYPE_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #include #include #include #include #include #include #include #include #include /************************************************************************ * * * Getting/Setting encoding meta tags * * * ************************************************************************/ /** * htmlGetMetaEncoding: * @doc: the document * * Encoding definition lookup in the Meta tags * * Returns the current encoding as flagged in the HTML source */ const xmlChar * htmlGetMetaEncoding(htmlDocPtr doc) { htmlNodePtr cur; const xmlChar *content; const xmlChar *encoding; if (doc == NULL) return(NULL); cur = doc->children; /* * Search the html */ while (cur != NULL) { if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) { if (xmlStrEqual(cur->name, BAD_CAST"html")) break; if (xmlStrEqual(cur->name, BAD_CAST"head")) goto found_head; if (xmlStrEqual(cur->name, BAD_CAST"meta")) goto found_meta; } cur = cur->next; } if (cur == NULL) return(NULL); cur = cur->children; /* * Search the head */ while (cur != NULL) { if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) { if (xmlStrEqual(cur->name, BAD_CAST"head")) break; if (xmlStrEqual(cur->name, BAD_CAST"meta")) goto found_meta; } cur = cur->next; } if (cur == NULL) return(NULL); found_head: cur = cur->children; /* * Search the meta elements */ found_meta: while (cur != NULL) { if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) { if (xmlStrEqual(cur->name, BAD_CAST"meta")) { xmlAttrPtr attr = cur->properties; int http; const xmlChar *value; content = NULL; http = 0; while (attr != NULL) { if ((attr->children != NULL) && (attr->children->type == XML_TEXT_NODE) && (attr->children->next == NULL)) { value = attr->children->content; if ((!xmlStrcasecmp(attr->name, BAD_CAST"http-equiv")) && (!xmlStrcasecmp(value, BAD_CAST"Content-Type"))) http = 1; else if ((value != NULL) && (!xmlStrcasecmp(attr->name, BAD_CAST"content"))) content = value; if ((http != 0) && (content != NULL)) goto found_content; } attr = attr->next; } } } cur = cur->next; } return(NULL); found_content: encoding = xmlStrstr(content, BAD_CAST"charset="); if (encoding == NULL) encoding = xmlStrstr(content, BAD_CAST"Charset="); if (encoding == NULL) encoding = xmlStrstr(content, BAD_CAST"CHARSET="); if (encoding != NULL) { encoding += 8; } else { encoding = xmlStrstr(content, BAD_CAST"charset ="); if (encoding == NULL) encoding = xmlStrstr(content, BAD_CAST"Charset ="); if (encoding == NULL) encoding = xmlStrstr(content, BAD_CAST"CHARSET ="); if (encoding != NULL) encoding += 9; } if (encoding != NULL) { while ((*encoding == ' ') || (*encoding == '\t')) encoding++; } return(encoding); } /** * htmlSetMetaEncoding: * @doc: the document * @encoding: the encoding string * * Sets the current encoding in the Meta tags * NOTE: this will not change the document content encoding, just * the META flag associated. * * Returns 0 in case of success and -1 in case of error */ int htmlSetMetaEncoding(htmlDocPtr doc, const xmlChar *encoding) { htmlNodePtr cur, meta; const xmlChar *content; char newcontent[100]; if (doc == NULL) return(-1); if (encoding != NULL) { snprintf(newcontent, sizeof(newcontent), "text/html; charset=%s", (char *)encoding); newcontent[sizeof(newcontent) - 1] = 0; } cur = doc->children; /* * Search the html */ while (cur != NULL) { if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) { if (xmlStrcasecmp(cur->name, BAD_CAST"html") == 0) break; if (xmlStrcasecmp(cur->name, BAD_CAST"head") == 0) goto found_head; if (xmlStrcasecmp(cur->name, BAD_CAST"meta") == 0) goto found_meta; } cur = cur->next; } if (cur == NULL) return(-1); cur = cur->children; /* * Search the head */ while (cur != NULL) { if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) { if (xmlStrcasecmp(cur->name, BAD_CAST"head") == 0) break; if (xmlStrcasecmp(cur->name, BAD_CAST"meta") == 0) goto found_meta; } cur = cur->next; } if (cur == NULL) return(-1); found_head: if (cur->children == NULL) { if (encoding == NULL) return(0); meta = xmlNewDocNode(doc, NULL, BAD_CAST"meta", NULL); xmlAddChild(cur, meta); xmlNewProp(meta, BAD_CAST"http-equiv", BAD_CAST"Content-Type"); xmlNewProp(meta, BAD_CAST"content", BAD_CAST newcontent); return(0); } cur = cur->children; found_meta: if (encoding != NULL) { /* * Create a new Meta element with the right attributes */ meta = xmlNewDocNode(doc, NULL, BAD_CAST"meta", NULL); xmlAddPrevSibling(cur, meta); xmlNewProp(meta, BAD_CAST"http-equiv", BAD_CAST"Content-Type"); xmlNewProp(meta, BAD_CAST"content", BAD_CAST newcontent); } /* * Search and destroy all the remaining the meta elements carrying * encoding informations */ while (cur != NULL) { if ((cur->type == XML_ELEMENT_NODE) && (cur->name != NULL)) { if (xmlStrcasecmp(cur->name, BAD_CAST"meta") == 0) { xmlAttrPtr attr = cur->properties; int http; const xmlChar *value; content = NULL; http = 0; while (attr != NULL) { if ((attr->children != NULL) && (attr->children->type == XML_TEXT_NODE) && (attr->children->next == NULL)) { value = attr->children->content; if ((!xmlStrcasecmp(attr->name, BAD_CAST"http-equiv")) && (!xmlStrcasecmp(value, BAD_CAST"Content-Type"))) http = 1; else { if ((value != NULL) && (!xmlStrcasecmp(attr->name, BAD_CAST"content"))) content = value; } if ((http != 0) && (content != NULL)) break; } attr = attr->next; } if ((http != 0) && (content != NULL)) { meta = cur; cur = cur->next; xmlUnlinkNode(meta); xmlFreeNode(meta); continue; } } } cur = cur->next; } return(0); } /** * booleanHTMLAttrs: * * These are the HTML attributes which will be output * in minimized form, i.e.