/// <summary> /// Serializes the input <typeparamref name="T"/> instance and returns a <see cref="Memory{T}"/> instance /// </summary> /// <typeparam name="T">The type of instance to serialize</typeparam> /// <param name="obj">The input instance to serialize</param> /// <returns>A <see cref="Memory{T}"/> instance containing the serialized data</returns> public static byte[] Serialize <T>(T obj) where T : new() { BinaryWriter writer = new BinaryWriter(BinaryWriter.DefaultSize); try { ObjectProcessor <T> .Instance.Serializer(obj, ref writer); return(writer.Span.ToArray()); } finally { writer.Dispose(); } }
/// <summary> /// Serializes the input <typeparamref name="T"/> instance to the target <see cref="Stream"/> /// </summary> /// <typeparam name="T">The type of instance to serialize</typeparam> /// <param name="obj">The input instance to serialize</param> /// <param name="stream">The <see cref="Stream"/> instance to use to write the data</param> public static void Serialize <T>(T obj, Stream stream) where T : new() { BinaryWriter writer = new BinaryWriter(BinaryWriter.DefaultSize); try { ObjectProcessor <T> .Instance.Serializer(obj, ref writer); stream.Write(writer.Span); } finally { writer.Dispose(); } }
/// <summary> /// Copies the contents of a given <see cref="Stream"/> to the target <see cref="BinaryPack.Serialization.Buffers.BinaryWriter"/> instance /// </summary> /// <param name="stream">The input <see cref="Stream"/> to read data from</param> /// <param name="writer">The target <see cref="BinaryPack.Serialization.Buffers.BinaryWriter"/> instance to write data to</param> public static void CopyTo(this Stream stream, ref BinaryPack.Serialization.Buffers.BinaryWriter writer) { byte[] buffer = ArrayPool <byte> .Shared.Rent(81920); try { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) != 0) { writer.Write(buffer.AsSpan(0, read)); } } finally { ArrayPool <byte> .Shared.Return(buffer); } }