|
| 1 | +namespace BioFSharp.IO.INSDC.Internal |
| 2 | + |
| 3 | +open System |
| 4 | +open System.Collections.Concurrent |
| 5 | +open System.IO |
| 6 | +open System.Xml.Serialization |
| 7 | + |
| 8 | +/// Internal helpers wrapping `System.Xml.Serialization.XmlSerializer` for the |
| 9 | +/// auto-generated INSDC types. Public modules in `BioFSharp.IO.INSDC` are thin |
| 10 | +/// wrappers over these functions, so the read/write/readString/writeString |
| 11 | +/// shape stays uniform across every INSDC entity. |
| 12 | +module XmlSerializer = |
| 13 | + |
| 14 | + let private serializerCache = ConcurrentDictionary<Type, XmlSerializer>() |
| 15 | + |
| 16 | + /// XmlSerializer construction is expensive; cache one instance per target type. |
| 17 | + let private getSerializer (t: Type) : XmlSerializer = |
| 18 | + serializerCache.GetOrAdd(t, fun t -> XmlSerializer(t)) |
| 19 | + |
| 20 | + /// Deserialize an INSDC record of type `'T` from the file at `filePath`. |
| 21 | + let read<'T> (filePath: string) : 'T = |
| 22 | + use stream = File.OpenRead(filePath) |
| 23 | + (getSerializer typeof<'T>).Deserialize(stream) :?> 'T |
| 24 | + |
| 25 | + /// Deserialize an INSDC record of type `'T` from an in-memory XML string. |
| 26 | + let readString<'T> (xml: string) : 'T = |
| 27 | + use reader = new StringReader(xml) |
| 28 | + (getSerializer typeof<'T>).Deserialize(reader) :?> 'T |
| 29 | + |
| 30 | + /// Serialize an INSDC record `value` to the file at `filePath`. |
| 31 | + let write<'T> (filePath: string) (value: 'T) : unit = |
| 32 | + use stream = File.Create(filePath) |
| 33 | + (getSerializer typeof<'T>).Serialize(stream, value) |
| 34 | + |
| 35 | + /// Serialize an INSDC record `value` to an XML string. |
| 36 | + let writeString<'T> (value: 'T) : string = |
| 37 | + use writer = new StringWriter() |
| 38 | + (getSerializer typeof<'T>).Serialize(writer, value) |
| 39 | + writer.ToString() |
0 commit comments