beef331 / website

Code for the official Nim programming language website
https://nim-lang.org
19 stars 1 forks source link

deser #68

Closed gabbhack closed 1 year ago

gabbhack commented 1 year ago

Name: deser

Author: gabbhack

Posting: Many serializers have already been written for Nim. You can probably find at least two serializers for each format.

The problem is that each library's API and customization options are different. You can't declare an object with renamed or skipped fields once and change the data format with one line.

Deser is a library for serializing and deserializing Nim data structures efficiently and generically.

Example:

import std/[
  options,
  times
]

import
  deser,
  deser_json

proc fromTimestamp(deserializer: var auto): Time =
  fromUnix(deserialize(int64, deserializer))

proc toTimestamp(self: Time, serializer: var auto) =
  serializer.serializeInt64(self.toUnix())

type
  ChatType = enum
    Private = "private"
    Group = "group"

  Chat {.renameAll(SnakeCase).} = object
    id: int64
    username {.skipSerializeIf(isNone).}: Option[string]
    created {.serializeWith(toTimestamp), deserializeWith(fromTimestamp).}: Time

    case kind {.renamed("type").}: ChatType
    of Private:
      firstName: string
      lastName {.skipSerializeIf(isNone).}: Option[string]
      bio {.skipSerializeIf(isNone).}: Option[string]
    of Group:
      title: string

# Use public to export deserialize or serialize procedures
# false by default
makeSerializable(Chat, public=true)
makeDeserializable(Chat, public=true)

const
  json = """
  {
    "id": 123,
    "username": "gabbhack",
    "created": 1234567890,
    "type": "private",
    "first_name": "Gabben"
  }
  """
  chat = Chat(
    id: 123,
    username: some "gabbhack",
    created: fromUnix(1234567890),
    kind: Private,
    firstName: "Gabben"
  )

echo Chat.fromJson(json)
echo chat.toJson()

Deser allows you to customize the de/serialization process, and the configuration will be applied to any parser.

Configuration is done with pragmas that are applied at compile-time. View available pragmas.

gabbhack commented 1 year ago

Sorry, found some critical bugs. I don't want to show an unready library.