Storable tuples and what is 'alignment'?

Glynn Clements glynn.clements@virgin.net
Tue, 6 Aug 2002 02:08:26 +0100


Hal Daume III wrote:

> 2) Could someone tell me what 'alignment' is

As the documentation says:

  Computes the alignment constraint of the argument. An alignment
  constraint x is fulfilled by any address divisible by x. The value of
  the argument is not used.

E.g. an alignment of 2 means that the data must be stored at an even
address, an alignment of 4 means that the data must be stored at an
address which is a multiple of 4, etc.

> and if this is the correct
> definition of a storable tuple:

Not really.

[Disclaimer: sample code is off the top of my head, untested, supplied
without warranty etc.]

> instance (Storable a, Storable b) => Storable (a,b) where
>     sizeOf (a,b) = sizeOf a + sizeOf b

You also need to allow for any padding which is required to satisfy
the alignment constraints of b, e.g.

	sizeOf (a,b) = sizeOf a + padding (a,b) + sizeOf b
		where padding (a,b) = (alignment b - sizeOf a `mod` alignment b) `mod` alignment b

>     alignment (a,b) = alignment a + alignment b

The alignment of the overall structure is determined by the alignment
of the first element. Subsequent elements are aligned (if necessary)
by the addition of padding between elements.

	alignment (a,_) = alignment a

>     peek ptr = do a <- peek (castPtr ptr)
> 		  b <- peek (castPtr ptr `plusPtr` sizeOf a)
> 		  return (a,b)

Again, there may be padding between a and b, i.e.

> 		  b <- peek (castPtr ptr `plusPtr` (sizeOf a + padding (a,b)))

>     poke ptr (a,b) = do poke (castPtr ptr) a
> 			poke (castPtr ptr `plusPtr` sizeOf a) b

Ditto.

> 			poke (castPtr ptr `plusPtr` (sizeOf a + padding (a,b))) b

-- 
Glynn Clements <glynn.clements@virgin.net>