Adding binarySize to Binary

David Roundy droundy at
Mon Feb 5 14:37:35 EST 2007

On Mon, Feb 05, 2007 at 06:37:38PM +0000, Neil Mitchell wrote:
> Hi
> >As it would operate on types rather than values (think sizeOf), the
> >result for "[a]" would probably be "(1, Nothing)" - a list takes one
> >byte at minimum and infinite bytes at maximum.
> That interface seems horrible - it looks like it will only be useful
> to a small number of people, and not be general at all. I really don't
> like the idea of an interface specifying a "fuzz factor" (which is
> what upper/lower bounds correspond to)

But often a fuzz factor is helpful, and it's always well-defined.  One
would often like to allocate padded structures so you can either modify
them in-place or have O(1) access to the elements, and you need a max size
for that.  The min size would be helpful for knowing when it's worth
padding.  It'd be heuristic, but if the max size is 1000 times larger than
the min size, you might not want to always allocate the maximum.

> In my BinaryDefer library I have a class BinaryDeferStatic:
> class BinaryDefer a => BinaryDeferStatic a where
>    -- | Must be a constant, must not examine first argument
>    getSize :: Proxy a -> Int
> This is for things which have a fixed and static size based on their type.

Except that the class-based approach is no good for a function (or data
type) which is intended to work with any data, even that which doesn't have
a static size.

> I could also see a reason for having a sizeOf method in the Binary
> class - where if unimplemented it just calls encode and then B.length.

Except that sizeOf as you describe it would operate on values rather than
on types, and as such would be useless for any of the uses of binarySize.

> Anything else just seems to be an ugly API...

I agree about the ugliness of binarySize as implemented (returning a
tuple).  Why not something like:

class Binary a where
   maxSize :: Proxy a -> Maybe Int
   maxSize _ = Nothing
   minSize :: Proxy a -> Int
   minSize _ = 0
   staticSize :: Proxy a -> Maybe Int
   staticSize p | maxSize p == Just (minSize p) = maxSize p
   staticSize _ = Nothing

Thus one can do nice things like make an array class that operates on any
Binary data, but can do nice tricks to optimize access times.  e.g. one
might want to allocate N*maxSize space, so you can have O(1) writes (in a
mutable array, or on disk).
David Roundy
Department of Physics
Oregon State University

More information about the Libraries mailing list