Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I agree. I think you may have misunderstood my comment. The wire representation should be read into memory via any byte order manipulations that are needed.


Why "every time you read the variable" then? You'd have a packed-binary-struct and a memory-representation-struct and conversions between them to use when reading or writing. I say "would", but I actually already do this. I have typedefs of the kind

  typedef union {
    uint8_t bytes[sizeof(uint64_t)];
    uint64_t native; /* alignment hint */
  } uint64le_t;
which I use in structs of my on-disk data structures.

  struct ondisk_range
  {
    uint64le_t start;
    uint64le_t end;
  };
Then for actually using that data:

  struct range
  {
    uint64_t start;
    uint64_t end;
  };
The conversion functions basically just call functions with these prototypes on the 2 fields:

  uint64_t le64_to_cpu(uint64le_t le_val);
  uint64le_t cpu_to_le64(uint64_t val);
Which internally just read out the byte array and turn it into an integer and vice versa.

(I also have static assertions for the expected size following each ondisk struct)

It'd be nicer to codify this as a DSL or something, but C's macro system really isn't up to the job.


adrianmsmith is suggesting that everytime the variable is read, the compiler inserts byte-swapping code. I disagree with that.


It would, in the worst case, not be worse than what the original poster is suggesting.

And at least in that case, the code would be more readable.

But, as the compiler knows more about what's going on (it's not just parsing and compiling a general expression with ORs and shifts) then it could well be faster (e.g. if there were a CPU instruction to do this, then it could be used, etc.).


I don't necessarily see a problem with that: it would avoid the messy cpu_to_le64 calls.


DSL?





Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: