How can I check if an argument is a valid IO list?

I maintain a library where a user can publish a message and I want to accept any iodata (I end up writing it to a TCP connection), but I would to return an error as soon as possible if someone passes an argument that is not valid iodata.

Rather than sending that data to a GenServer and dealing with a badarg error, I would like to guard against the bad argument at the edge of my API and return a descriptive error message.

Is there a way to pattern match against iodata? Or check it in a guard clause? Or even check it in the function body?

The specification for iodata is:

byte()	0..255
iodata()	iolist() | binary()
iolist()	maybe_improper_list(byte() | binary() | iolist(), binary() | [])

So to check a list if its a valid iodata I think you’d have to traverse it and check each entry which might be more expensive than just handling the error.

3 Likes