[comp.lang.pascal] ordinal types and memory buffers

chad@lakesys.UUCP (D. Chadwick Gibbons) (07/20/89)

	Many applications benefit from the use of large memory buffers
for such things as screen windows, database record buffers, etc.  Most of
the time a programmer would assign part of the buffer to an ordinal type
(real, integer, etc.)  To do this normally requires a move instruction,
given the following code:

TYPE
  MemoryBufferType = ARRAY [1..MaxMemorySize] OF BYTE;

VAR
  MemoryBuffer : MemoryBufferType;
  RealVar      : REAL;

BEGIN
  .
  .
  .
  RealVar := 17;
  .
  .
  .
  MOVE(RealVar, MemoryBuffer[RealVarOffset], SIZEOF(RealVar));
  .
  .
  .
END;

However, using MOVE on ordinal types is not the fastest, nor the most
logical method of data assignment.  Strong typecasting (which Turbo
Pascal V5.0/5.5 does NOT have) would allow one to replace this line for
the move instruction:

  REAL(MemoryBuffer[RealVarOffset]) := RealVar;

Unfortunately, the typecasting mechanism is not strong enough to do this,
since the size of a byte is less than that of a real.  There is, however,
another way around this.  Consider this example:

PROGRAM Foo;

TYPE
  RealPtr = ^REAL;

VAR
  MemoryBuffer : ARRAY [1..2048] OF BYTE;
  RealVar      : REAL;

BEGIN
  .
  .
  .
  RealVar := 17;
  .
  .
  .
  RealPtr(@MemoryBuffer[RealVarOffset])^ := RealVar;
  .
  .
  .
END.

Here we can tricked the compiler into allowing the assignment by casting
a pointer to the memory buffer, rather than the actual array itself.
This works rather well: the assignment above is over four times faster
than a given move instruction, and produces assembly code with half as
few instructions.

	While the speed increase is dramatic and worth the use of the
pointer conversion method, it is syntatically ugly and a pain to use.  A
typecast allowing the compiler to convert segments of a large array would
be a useful addition to future versions of the system.  The size
difference checking should be slightly more intelligent--check the size
of the overall object, not just the base ordinal type.

	Anyone else have any comments on this?  Perhaps a better way to
assign sections of memory buffers to another ordinal type?  (When it
comes to records, and other user-defined types, move wins, no contest.)
-- 
D. Chadwick Gibbons, chad@lakesys.lakesys.com, ...!uunet!marque!lakesys!chad