using Google.Protobuf; using System; using System.Collections.Generic; using System.IO; namespace bts.utils.proto { static class StreamHelper { public static void WriteProtos(Stream stream, T value) where T : Google.Protobuf.IMessage => WriteProtos(stream, new[] { value }); public static void WriteProtos(Stream stream, IEnumerable source) where T : Google.Protobuf.IMessage { foreach (var value in source) Google.Protobuf.MessageExtensions.WriteDelimitedTo(value, stream); } public static IEnumerable ReadProtos(byte[] bytes) where T : IMessage, new() => ReadProtos(new MemoryStream(bytes)); public static IEnumerable ReadProtos(Stream fs) where T : IMessage, new() { var parser = ProtoHelper.parser; while (fs.Position < fs.Length) { T val; try { val = parser.ParseDelimitedFrom(fs); } catch { break; } yield return val; } } public static byte[] ToDelimitedByteArray(IEnumerable source) where T : IMessage { using (var stream = new MemoryStream()) { foreach (var v in source) v.WriteDelimitedTo(stream); return stream.ToArray(); } } public static class ProtoHelper where T : IMessage, new() { public static readonly MessageParser parser = new MessageParser(() => new T()); } } static class FileStreamHelper { public static List ReadProtos(string path, bool check_existence_first = true) where T : Google.Protobuf.IMessage, new() { if (!check_existence_first || File.Exists(path)) { var fs = SafeOpen(path, FileMode.Open, FileAccess.Read, FileShare.Read); if (fs != null) { using (fs) return new List(StreamHelper.ReadProtos(fs)); } } return new List(0); } public static void AppendProtos(string path, T value) where T : IMessage => AppendProtos(path, new[] { value }); public static void AppendProtos(string path, IEnumerable source) where T : IMessage { using (var fs = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read)) StreamHelper.WriteProtos(fs, source); } public static void WriteProtos(string path, IEnumerable source) where T : IMessage { using (var fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read)) StreamHelper.WriteProtos(fs, source); } public static FileStream SafeOpen(string path, FileMode mode, FileAccess access, FileShare share) => SafeOpen(path, mode, access, share, out string _); public static FileStream SafeOpen(string path, FileMode mode, FileAccess access, FileShare share, out string error_message) { FileStream rv; try { rv = File.Open(path, mode, access, share); error_message = null; } catch (Exception ex) { error_message = ex.ToString(); rv = null; } return rv; } public static class ProtoHelper where T : IMessage, new() { public static readonly string default_file_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), new T().Descriptor.Name); } } }