Create test input for a Bytes decoder/encoder?

Hi,

I’m doing my first experiments with elm and elm/bytes. I’m creating encoders/decoders and looking for an easy way to give them input data while I’m learning and testing.

Decoders (and a Bytes encoder) accept a Bytes type, but this type seems to be (justifiably) opaque. Is there a way to create a Bytes type directly? Is there another approach to experimenting with encoders/decoders?

For example, if I’m naively encoding an Int:

type alias IntThing =
    { -- more fields later
      data : Int
    }

toIntThingEncoder : IntThing -> Encoder
toIntThingEncoder thing =
    Encode.unsignedInt8 thing.data

I can easily experiment with it using something like:

toIntThingEncoder { data = 3 }

If, however, if I’m using a Bytes type:

type alias ByteThing =
    { -- more fields later
      data : Bytes
    }


toByteThingEncoder : ByteThing -> Encoder
toByteThingEncoder thing =
    Encode.bytes thing.data

I’m not sure of an easy way to get data to feed into the encoder:

encode (toByteThingEncoder ?)

Any insight would be much appreciated.

Thanks!

I’m not sure to understand what you mean.
The way to create Bytes is to use Bytes.Encode.encode, as you know, so you can do:

encode (toByteThingEncoder {data = encode (Encode.unsignedInt8 3)} )

or using any other Encode function which produces an Encoder. You could use for example sequence with a list of unsigned byte values like

{ data = encode <| Encode.sequence <| List.map Encode.unsignedInt8 [0x42, 0xff, ... ] }

You would most likely need a way to also encode the width though.

Ah, you’re right! I didn’t think to use a Bytes.Encode.encode.

Thank you for showing the example with List.map! That was a missing piece, and I think it would’ve taken me a long time to figure that out.

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.