Delphi: adequate data structure for headered blocks

76 Views Asked by At

As far as I know one of the most used data structure cannot represented by an adequate dta structure directly: we speak about blocks or streams with header.

Let's imagine a simple image format, where the first integer represents the kind of image (Grayscale, RGB, CMYK etc.), the second the bit depth, the third and fourth the width and height respectively, and all the subsequent bytes represent the bitmap data itself.

Something like this:

TSimpleImage = packed record
  imageType: integer;
  bitDepth: integer;
  width: integer;
  height: integer;
  data: array [0 .. high(integer)] of byte; // actual image data with variable length;
end;

Of course, as we cannot predict the size in compile time we define the maximum possible value here. The problem is that even if this structure is perfect usable, it's neither elegant nor safe. That is, it never can be used directly, just dereferenced, or passing as var or const variable to a procedure – but obviously no compile warnings or errors will occur when we accidentally omit this rule.

Is there something more elegant which can be used for headers + blocks (data streams)?

UPDATE: It seems that the term 'stream' is a little ambigous here. A stream doesn't need necessarily to be something like TStream which have to get read sequentially. It can reside in memory as well, e.g. as part of a RAM window of an MMF. So there is no sequential reading here, all the byte of the block or stream can be accessed immediately and randomly.

0

There are 0 best solutions below