Skip to content

Commit

Permalink
Tidy
Browse files Browse the repository at this point in the history
  • Loading branch information
bartelink committed Jan 24, 2024
1 parent 39cd706 commit 102decc
Showing 1 changed file with 4 additions and 13 deletions.
17 changes: 4 additions & 13 deletions src/FsCodec.SystemTextJson/UnionOrTypeSafeEnumConverterFactory.fs
Original file line number Diff line number Diff line change
@@ -1,28 +1,19 @@
namespace FsCodec.SystemTextJson

open System
open System.Linq.Expressions
open System.Text.Json.Serialization

type internal ConverterActivator = delegate of unit -> JsonConverter

type UnionOrTypeSafeEnumConverterFactory(typeSafeEnum, union) =
inherit JsonConverterFactory()

static let hasConverterAttribute = memoize (fun (t: Type) -> t.IsDefined(typeof<JsonConverterAttribute>, true))
static let hasConverterAttribute = memoize (fun (t: System.Type) -> t.IsDefined(typeof<JsonConverterAttribute>, true))

override _.CanConvert(t: Type) =
not (t.IsGenericType && let gtd = t.GetGenericTypeDefinition() in gtd = typedefof<option<_>> || gtd = typedefof<list<_>>)
override _.CanConvert t =
not (t.IsGenericType && let g = t.GetGenericTypeDefinition() in g = typedefof<option<_>> || g = typedefof<list<_>>)
&& FsCodec.Union.isUnion t
&& not (hasConverterAttribute t)
&& ((typeSafeEnum && union)
|| typeSafeEnum = FsCodec.Union.isNullary t)

override _.CreateConverter(t, _options) =
let openConverterType = if FsCodec.Union.isNullary t then typedefof<TypeSafeEnumConverter<_>> else typedefof<UnionConverter<_>>
let constructor = openConverterType.MakeGenericType(t).GetConstructors() |> Array.head
let newExpression = Expression.New(constructor)
let lambda = Expression.Lambda(typeof<ConverterActivator>, newExpression)

let activator = lambda.Compile() :?> ConverterActivator
activator.Invoke()
openConverterType.MakeGenericType(t).GetConstructors().[0].Invoke[||] :?> _

0 comments on commit 102decc

Please sign in to comment.