Possible errors that can occur when decoding.
CustomError - An error caused by andThen returning an Err value.DataCorrupted - This most likely will occur if you make breaking changes to your codec and try to decode old data*. Have a look at How do I change my codecs and still be able to decode old data? in the readme for how to avoid introducing breaking changes.SerializerOutOfDate - When encoding, this package will include a version number. This makes it possible for me to make improvements to how data gets encoded without introducing breaking changes to your codecs. This error then, says that you're trying to decode data encoded with a newer version of elm-serialize.*It's possible for corrupted data to still succeed in decoding (but with nonsense Elm values). This is because internally we're just encoding Elm values and not storing any kind of structural information. So if you encoded an Int and then a Float, and then tried decoding it as a Float and then an Int, there's no way for the decoder to know it read the data in the wrong order.
Run a Codec to turn a sequence of bytes into an Elm value.
Run a Codec to turn a String encoded with encodeToString into an Elm value.
Convert an Elm value into a sequence of bytes.
Convert an Elm value into a string. This string contains only url safe characters, so you can do the following:
import Serlialize as S
myUrl =
"www.mywebsite.com/?data=" ++ S.encodeToString S.float 1234and not risk generating an invalid url.
Codec for serializing () (aka Unit).
Since the Unit type only has one possible value, we don't need to encode anything in order to represent it.
Codec for serializing Bytes.
This is useful in combination with mapValid for encoding and decoding data using some specialized format.
import Image exposing (Image)
import Serialize as S
imageCodec : S.Codec String Image
imageCodec =
S.bytes
|> S.mapValid
(Image.decode >> Result.fromMaybe "Failed to decode PNG image.")
Image.toPngCodec for serializing an integer ranging from 0 to 255. This is useful if you have a small integer you want to serialize and not use up a lot of space.
import Serialize as S
type alias Color =
{ red : Int
, green : Int
, blue : Int
}
color : S.Codec Color
color =
Color.record Color
|> S.field .red byte
|> S.field .green byte
|> S.field .blue byte
|> S.finishRecordCodec for serializing a Maybe
import Serialize as S
maybeIntCodec : S.Codec (Maybe Int)
maybeIntCodec =
S.Maybe S.IntCodec for serializing a List
import Serialize as S
listOfStringsCodec : S.Codec (List String)
listOfStringsCodec =
S.list S.stringCodec for serializing a Dict
import Serialize as S
type alias Name =
String
peoplesAgeCodec : S.Codec (Dict Name Int)
peoplesAgeCodec =
S.dict S.string S.intCodec for serializing a tuple with 2 elements
import Serialize as S
pointCodec : S.Codec ( Float, Float )
pointCodec =
S.tuple S.float S.floatCodec for serializing a tuple with 3 elements
import Serialize as S
pointCodec : S.Codec ( Float, Float, Float )
pointCodec =
S.tuple S.float S.float S.floatCodec for serializing a Result
A codec for serializing an item from a list of possible items. If you try to encode an item that isn't in the list then the first item is defaulted to.
import Serialize as S
type DaysOfWeek
= Monday
| Tuesday
| Wednesday
| Thursday
| Friday
| Saturday
| Sunday
daysOfWeekCodec : S.Codec DaysOfWeek
daysOfWeekCodec =
S.enum Monday [ Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday ]A partially built Codec for a record.
Start creating a codec for a record.
import Serialize as S
type alias Point =
{ x : Int
, y : Int
}
pointCodec : S.Codec Point
pointCodec =
S.record Point
-- Note that adding, removing, or reordering fields will prevent you from decoding any data you've previously encoded.
|> S.field .x S.int
|> S.field .y S.int
|> S.finishRecordAdd a field to the record we are creating a codec for.
Finish creating a codec for a record.
A partially built codec for a custom type.
Starts building a Codec for a custom type.
You need to pass a pattern matching function, see the FAQ for details.
import Serialize as S
type Semaphore
= Red Int String Bool
| Yellow Float
| Green
semaphoreCodec : S.Codec Semaphore
semaphoreCodec =
S.custom
(\redEncoder yellowEncoder greenEncoder value ->
case value of
Red i s b ->
redEncoder i s b
Yellow f ->
yellowEncoder f
Green ->
greenEncoder
)
-- Note that removing a variant, inserting a variant before an existing one, or swapping two variants will prevent you from decoding any data you've previously encoded.
|> S.variant3 Red S.int S.string S.bool
|> S.variant1 Yellow S.float
|> S.variant0 Green
-- It's safe to add new variants here later though
|> S.finishCustomDefine a variant with 0 parameters for a custom type.
Define a variant with 1 parameters for a custom type.
Define a variant with 2 parameters for a custom type.
Define a variant with 3 parameters for a custom type.
Define a variant with 4 parameters for a custom type.
Define a variant with 5 parameters for a custom type.
Define a variant with 6 parameters for a custom type.
Define a variant with 7 parameters for a custom type.
Define a variant with 8 parameters for a custom type.
Finish creating a codec for a custom type.
Map from one codec to another codec
import Serialize as S
type UserId
= UserId Int
userIdCodec : S.Codec UserId
userIdCodec =
S.int |> S.map UserId (\(UserId id) -> id)Note that there's nothing preventing you from encoding Elm values that will map to some different value when you decode them.
I recommend writing tests for Codecs that use map to make sure you get back the same Elm value you put in.
Here's some helper functions to get you started.
Map from one codec to another codec in a way that can potentially fail when decoding.
-- Email module is from https://package.elm-lang.org/packages/tricycle/elm-email/1.0.2/
import Email
import Serialize as S
emailCodec : S.Codec String Float
emailCodec =
S.string
|> S.mapValid
(\text ->
case Email.fromString of
Just email ->
Ok email
Nothing ->
Err "Invalid email"
)
Email.toStringNote that there's nothing preventing you from encoding Elm values that will produce Err when you decode them.
I recommend writing tests for Codecs that use mapValid to make sure you get back the same Elm value you put in.
Here's some helper functions to get you started.
Handle situations where you need to define a codec in terms of itself.
import Serialize as S
type Peano
= Peano (Maybe Peano)
{-| The compiler will complain that this function causes an infinite loop.
-}
badPeanoCodec : S.Codec Peano
badPeanoCodec =
S.maybe badPeanoCodec |> S.map Peano (\(Peano a) -> a)
{-| Now the compiler is happy!
-}
goodPeanoCodec : S.Codec Peano
goodPeanoCodec =
S.maybe (S.lazy (\() -> goodPeanoCodec)) |> S.map Peano (\(Peano a) -> a)Warning: This is not stack safe.
In general if you have a type that contains itself, like with our the Peano example, then you're at risk of a stack overflow while decoding. Even if you're translating your nested data into a list before encoding, you're at risk, because the function translating back after decoding can cause a stack overflow if the original value was nested deeply enough. Be careful here, and test your codecs using elm-test with larger inputs than you ever expect to see in real life.
A value that knows how to encode and decode an Elm data structure.