Boost logo

Boost Users :

From: Dave Dribin (dave-ml_at_[hidden])
Date: 2006-07-20 09:29:43


On Jul 19, 2006, at 10:20 PM, me22 wrote:
> The original discussion mentioned something that appears similar and
> was handled by templating the full struct, along the lines of the
> following:

Hmmm... I'm not sure that would help in my case. The endianness need
not be different for unions to be useful.

> Can you explain what your use case is for this union?

Sure, I'll go over the details in a second. But what's the use case/
rationale for *not* wanting to support unions?

I was actually porting some code that directly reads a disk formated
as Apple's HFS+ filesystem, where endian and alignment are
paramount. Apple provides structures that describes the on-disk
format in /usr/include/hfs/hfs_format.h. You can see it here, since
it's open source:

   <http://darwinsource.opendarwin.org/10.4.6.ppc/xnu-792.6.70/bsd/
hfs/hfs_format.h>

Of course, these structures assume that you're on a big-endian
machine. But I needed to port code from PowerPC to Intel for the new
Macs. A few unions are used in that header, for example:

/* A generic Attribute Record*/
union HFSPlusAttrRecord {
         u_int32_t recordType;
         HFSPlusAttrInlineData inlineData; /* NOT USED */
         HFSPlusAttrData attrData;
         HFSPlusAttrForkData forkData;
         HFSPlusAttrExtents overflowExtents;
};
typedef union HFSPlusAttrRecord HFSPlusAttrRecord;

Which has integer types mixed with other structures, such as:

/*
  * Atrributes B-tree Data Record
  *
  * For small attributes, whose entire value is stored
  * within a single B-tree record.
  */
struct HFSPlusAttrData {
         u_int32_t recordType; /* == kHFSPlusAttrInlineData */
         u_int32_t reserved[2];
         u_int32_t attrSize; /* size of attribute data in
bytes */
         u_int8_t attrData[2]; /* variable length */
};
typedef struct HFSPlusAttrData HFSPlusAttrData;

Since my endian classes had no constructors, and hence supported
unions, I was able to get the whole file to work as endian-neutral by
doing some nasty preprocessor magic, such as:

#define u_int32_t ubig4_t
// #define's for other types used ...

#include "hfs_format.h"

#undef u_int32_t
// #undef's for other types used ...

Then, all the old legacy code basically just worked on Intel without
modification.

-Dave


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net