coers
A small library for coercion to primitive Erlang types
About
Coers is a very small library to provide small coercion on primitive types in Erlang. While originally created for use with internal tools at derniercri.io, it is useful for Erlang/BEAM projects that consume arbitrary string data from external systems that don’t support Erlang terms, JSON, or industry standard data serialisation.
Build & Test
$ rebar3 compile
$ rebar3 checkThe later includes not only unit tests, but also other checks and coverage assessment.
Usage
Each coercion is wrapped into a special record:
-record(result, {
value :: term(),
error :: term(),
}).
If a coercion fails, the value field is undefined and the error field is populated with
an appropriate error. If the coersion succeed, the value field becomes the coerced data and the
error field is undefined.
You can use these functions from the coers API to examine the coercion status:
coers:value(Result)coers:error(Result)coers:has_error(Result)
For example :
1> R1 = coers:to_int("10").
{result,10,undefined}
2> R2 = coers:to_int("foo").
{result,undefined,{badarg,"Could not convert \"foo\" (type any) to int"}}Additional convenience functions are available via the results library:
3> results:has_values([R1, R2]).
[true,false]
4> results:has_errors([R1, R2]).
[false,true]
5> results:values([R1, R2]).
[10,undefined]Note that fractions are supported (via the rationals Erlang library):
6> coers:to_rational("1/42").
{result,{fraction,1,42},undefined}
7> coers:to_rational(<<"1/42">>).
{result,{fraction,1,42},undefined}
8> coers:to_rational({1, 42}).
{result,{fraction,1,42},undefined}Example usgage in LFE when reading data from the Extempore music system:
(defun ->lfe (bitstr)
(case bitstr
(#"NIL" 'nil)
(_ (cond ((?= `#(result ,val undefined) (coers:->int bitstr))
val)
((?= `#(result ,val undefined) (coers:->float bitstr))
val)
((?= `#(result ,val undefined) (coers:->bool bitstr))
val)
((?= `#(result ,val undefined) (coers:->string bitstr))
val)
('true bitstr)))))License
MIT
Copyright © 2020-2021, Erlang-Aided Enrichment Center
Copyright © 2016, Xavier van De Woestyne