Example #1
0
static int
ah_get(istream &is, AHRecord &rec)
{
	// read header+data from an istream
    
	int ndata, dtype;

// read header *********************************
	char hbuf[HEADER_SIZE];
	XDR xdrs;

	// read a header from an istream
	is.read(hbuf, HEADER_SIZE);

	if (is.eof()) {

		// no bytes read -> proper EOF
		// otherwise -> unexpected EOF
		return is.gcount()==0 ? AH_SUCCESS : AH_ERROR;
	}

	if (is.fail()) {
		cerr << "failed to read header" << endl;
		return AH_ERROR;
	}

	xdrmem_create(&xdrs, hbuf, (unsigned int) HEADER_SIZE, XDR_DECODE);

	int status = AH_SUCCESS;

	// read a header from an XDR stream
	if ( ! xdr_Header(&xdrs, &rec, ndata, dtype))
		status = AH_ERROR;

	// check data type -> XXX do this inside xdr_Header
//      if ( ! is_valid_data_type(rec->type))
//              status = AH_ERROR;

	if (status == AH_SUCCESS && is.eof()) // XXX XXX XXX XXX XXX XXX XXX
		return AH_SUCCESS;      // proper EOF

// read data samples ***************************
	size_t bufsize = buflen(ndata, dtype);

	vector<char> dbuf(bufsize);
	char *buf = &dbuf[0];
	is.read(buf, bufsize);

	// While reading data we shall never reach EOF
	if (is.eof())
		return AH_ERROR;        // unexpected EOF
	if (is.fail())
		return AH_ERROR;        // <- obsolete ???

	xdrmem_create(&xdrs, buf, bufsize, XDR_DECODE);

	int n = ndata;

	switch (dtype) {
	case AH_DATATYPE_FLOAT:
		{
		// allocate new data
		FloatArray *arr = new FloatArray(n);
		rec.setData(arr);
		float *f = (float*)(arr->data());
# ifdef IEEE_INTEL
		float *f0 = (float*) xdrs.x_private;
		char  *b2 = (char*) f;
# endif

		// read data
# ifdef IEEE_SPARC
		assert(sizeof(float)==4);
		// copy without swapping
		memcpy(f, (void*) xdrs.x_private, n*sizeof(float));
# else
		while (n--)
		{
#   ifdef IEEE_INTEL
			char *b1 = (char*)(++f0);

			*(b2++) = *(--b1);
			*(b2++) = *(--b1);
			*(b2++) = *(--b1);
			*(b2++) = *(--b1);
#   else
			if ( ! xdr_float(&xdrs, f++))
				cerr << "error while reading data" << endl;
#   endif
		}
# endif
		}
		break;

	case AH_DATATYPE_COMPLEX:
/*
		{
		float re, im;

		// allocate new data
		Complex *c = new Complex [n];
		rec->xdata   = (void*) c;

		// read data
		for (int i=0; i<n; i++, c++)
		{
			re = im = 0.0;

			if ( ! xdr_float(&xdrs, &re) ||
			     ! xdr_float(&xdrs, &im))
				ah_error(1, "error while reading data");

			*c = Complex(re, im);
		}
		}
*/
		break;

	default:
		cerr << "ah_error_illegal_data_type XY" << endl;
		break;
	}

	xdr_destroy(&xdrs);

	return status;
}