Encoder
This module implements a serializer for different types and objects into KDL documents, nodes and values:
- char
- bool
- Option[T]
- SomeNumber
- StringTableRef
- enum and HoleyEnum
- string and cstring
- KdlVal (object variant)
- seq[T] and array[I, T]
- set[Ordinal], HashSet[A] and OrderedSet[A]
- Table[string, T] and OrderedTable[string, T]
- object, ref and tuple (including object variants)
- Plus any type you implement.
Use encodeKdlDoc, encodeKdlNode and encodeKdlVal correspondingly.
Example:
import src/kdl/encoder import std/options import kdl type Package = object name*, version*: string authors*: Option[seq[string]] description*, licenseFile*, edition*: Option[string] const doc = parseKdl(""" name "kdl" version "0.0.0" authors { - "Kat Marchán <kzm@zkat.tech>" } description "kats document language" licenseFile "LICENSE.md" edition "2018" """) const obj = Package( name: "kdl", version: "0.0.0", authors: @["Kat Marchán <kzm@zkat.tech>"].some, description: "kats document language".some, licenseFile: "LICENSE.md".some, edition: "2018".some ) assert obj.encodeKdlDoc() == doc
Custom Encode Hooks
If you need to encode a specific type in a specific way you may create a custom encode hooks.
To do so, you'll have to overload the encodeKdl procedure with the following signature:
proc encodeKdl*(a: MyType, v: var KdlSome)Where KdlSome is one of KdlDoc, KdlNode or KdlVal. Note: to understand it better think about it like encoding `a` into `v`, where `v` can be a KDL document, node or value.
Example:
import src/kdl/encoder import std/times import kdl proc encodeKdl*(a: DateTime, v: var KdlDoc) = v = @[ initKNode("year", args = @[encodeKdlVal(a.year)]), initKNode("month", args = @[encodeKdlVal(a.month)]), initKNode("day", args = @[encodeKdlVal(a.monthday)]), initKNode("hour", args = @[encodeKdlVal(a.hour)]), initKNode("minute", args = @[encodeKdlVal(a.minute)]), initKNode("second", args = @[encodeKdlVal(a.second)]), initKNode("nanosecond", args = @[encodeKdlVal(a.nanosecond)]), ] const doc = parseKdl(""" "year" 2022 "month" "October" "day" 15 "hour" 12 "minute" 4 "second" 0 "nanosecond" 0 """) assert dateTime(2022, mOct, 15, 12, 04).encodeKdlDoc() == doc
Procs
proc encodeKdl(a: KdlDoc; v: var KdlNode; name: string) {....raises: [], tags: [], forbids: [].}
- Source Edit
proc encodeKdl(a: KdlNode; v: var KdlNode; name: string) {....raises: [], tags: [], forbids: [].}
- Source Edit
proc encodeKdl(a: KdlVal; v: var KdlNode; name: string) {....raises: [], tags: [], forbids: [].}
- Source Edit
proc encodeKdl(a: SomeTable[string, auto] or SomeSet[auto]; v: var KdlNode; name: string)
- Source Edit
proc encodeKdlDoc(a: auto): KdlDoc
- Source Edit
proc encodeKdlNode(a: auto; name: string): KdlNode
- Source Edit
proc encodeKdlVal(a: auto): KdlVal
- Source Edit