-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
4 additions
and
13 deletions.
There are no files selected for viewing
17 changes: 4 additions & 13 deletions
17
src/FsCodec.SystemTextJson/UnionOrTypeSafeEnumConverterFactory.fs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[||] :?> _ |