peteroupc / CBOR

A C# implementation of Concise Binary Object Representation (RFC 8949).
The Unlicense
206 stars 29 forks source link

How to convert a type in F# to CBORobject? #41

Closed l1x closed 4 years ago

l1x commented 4 years ago

I was wondering if there is a way to convert a simple type in F# to a CBORobject.

type HitType = { hitHostname : string; hitMemoryUsed : float; hitPage : string; }

Let me know if this is supported by this project. Thanks!

peteroupc commented 4 years ago

Did you try CBORObject.FromObject?

l1x commented 4 years ago

I did.

let exampleHit = { hitHostname = "google.com"; hitMemoryUsed = 0.1234; hitPage = "index.html"}

let cborTest() =
  Console.WriteLine("{0}", "Cbor test")
  let cbor = CBORObject.FromObject(exampleHit)
  let encoded = cbor.EncodeToBytes()
  let buffer = new MemoryStream()
  buffer.Write(encoded, 0, encoded.Length)
  buffer.Seek(int64(0), SeekOrigin.Begin) |> ignore
  let decoded = CBORObject.Read(buffer);
  Console.WriteLine("{0}", decoded)

Output:

Cbor test
{}

Maybe I am missing something.

peteroupc commented 4 years ago

This is currently not supported with just CBORObject.FromObject(obj)

HitType has only read-only properties, and CBORObject.FromObject supports read-only properties of a type only if that type is compiler-generated (e.g., in the case of anonymous types). I will see what can be done to support F# types in the next version.

In the meantime, try using the overload that takes a CBORTypeMapper.

peteroupc commented 4 years ago

Released version 4.1.0 which should address this issue.