Skip to content

Roundtrip fails when used on Table with case object as key #59

@yuanweixin

Description

@yuanweixin

So, if I

  1. define a case object
  2. use the case object as key in a Table
  3. serialize the table
  4. deserialize the table

The code fails at step 4 because it represents the key as a json object.

In example below, the generated json is:
{{"kind":"TermS","term":42}:42}

Can user expect the default json ser/deser to cover such a use case? If not, what's the correct way to use the library so that roundtripping works?

import jsony, tables, hashes

type SymbolKind* {.pure.} = enum
  TermS

type Symbol* = object
  case kind*: SymbolKind
  of SymbolKind.TermS:
    term*: int

proc hash*(x: Symbol): Hash =
  var h: Hash = 0
  h = h !& hash(x.kind)
  case x.kind 
  of TermS:
    h = h !& hash(x.term)
  else:
    discard
  return !$h

proc `==`*(a,b: Symbol) : bool = 
  return a.kind == b.kind and a.term == b.term

var t : Table[Symbol, int]

t[Symbol(kind: TermS, term: 42)] = 42

let str = t.toJson()
echo str
discard str.fromJson(Table[Symbol, int])

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions