#region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0 /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System.IO; using CSharpTest.Net.IO; namespace CSharpTest.Net.Serialization { /// Provides serialization for a type public interface ISerializer { /// Writes the object to the stream void WriteTo(T value, Stream stream); /// Reads the object from a stream T ReadFrom(Stream stream); } /// /// Returns all bytes in the stream, or writes all bytes to the stream /// public class BytesSerializer : ISerializer { /// Gets a singleton of the BytesSerializer class public static readonly ISerializer RawBytes = new BytesSerializer(); void ISerializer.WriteTo(byte[] value, Stream stream) { stream.Write(value, 0, value.Length); } byte[] ISerializer.ReadFrom(Stream stream) { return IOStream.ReadAllBytes(stream); } } #if !NET20 /// /// Extension methods used with ISerializer<T> for byte[] transformations /// public static class SerializerExtensions { /// /// Enables creation of the type TKey from an array of bytes /// public static TKey FromByteArray(this ISerializer ser, byte[] value) { using (MemoryStream ms = new MemoryStream(value)) return ser.ReadFrom(ms); } /// /// Enables creation of an array of bytes from type TKey /// public static byte[] ToByteArray(this ISerializer ser, TKey value) { using (MemoryStream ms = new MemoryStream()) { ser.WriteTo(value, ms); return ms.ToArray(); } } } #endif }