using System; using System.IO; namespace Google.Protobuf { /// /// A parser for a specific message type. /// /// ///

/// This delegates most behavior to the /// implementation within the original type, but /// provides convenient overloads to parse from a variety of sources. ///

///

/// Most applications will never need to create their own instances of this type; /// instead, use the static Parser property of a generated message type to obtain a /// parser for that type. ///

///
/// The type of message to be parsed. public sealed class MessageParser where T : IMessage { private readonly Func factory; /// /// Creates a new parser. /// /// /// The factory method is effectively an optimization over using a generic constraint /// to require a parameterless constructor: delegates are significantly faster to execute. /// /// Function to invoke when a new, empty message is required. public MessageParser(Func factory) { this.factory = factory; } /// /// Creates a template instance ready for population. /// /// An empty message. internal T CreateTemplate() { return factory(); } /// /// Parses a message from a byte array. /// /// The byte array containing the message. Must not be null. /// The newly parsed message. public T ParseFrom(byte[] data) { ThrowHelper.ThrowIfNull(data, "data"); T message = factory(); message.MergeFrom(data); return message; } public T ParseFrom(ByteString data) { ThrowHelper.ThrowIfNull(data, "data"); T message = factory(); message.MergeFrom(data); return message; } public T ParseFrom(Stream input) { T message = factory(); message.MergeFrom(input); return message; } public T ParseDelimitedFrom(Stream input) { T message = factory(); message.MergeDelimitedFrom(input); return message; } public T ParseFrom(CodedInputStream input) { T message = factory(); message.MergeFrom(input); return message; } } }