Lw.Rc Representation Clauses - JulTob/Ada GitHub Wiki

One very interesting feature of the language is that, unlike C, for example, there are no data representation constraints unless specified by the developer. This means that the compiler is free to choose the best trade-off in terms of repre- sentation vs. performance. Let’s start with the following example:

type R is record
  V : Integer range 0 .. 255;
  B1 : Boolean;
  B2 : Boolean;
  end record
with Pack;

In Ada, it’s the other way around: the developer specifies the range of values required and the compiler decides how to represent things, optimizing for speed or size. The Pack aspect declared at the end of the record specifies that the compiler should optimize for size even at the expense of decreased speed in accessing record components.

Other representation clauses can be specified as well, along with compile-time consistency checks between require- ments in terms of available values and specified sizes. This is particularly useful when a specific layout is necessary; for example when interfacing with hardware, a driver, or a communication protocol. Here’s how to specify a specific data layout based on the previous example:

for R use record
  -- Occupy the first bit of the first byte.
  B1 at 0 range 0 .. 0;

  -- Occupy the last 7 bits of the first byte,
  -- as well as the first bit of the second byte.
  V at 0 range 1 .. 8;

  -- Occupy the second bit of the second byte.
  B2 at 1 range 1 .. 1;
end record;

We omit the with Pack directive and instead use a record representation clause following the record declaration.