static T SerializeZeroFormatter <T>(T original) { // Console.WriteLine("ZeroFormatter"); T copy = default(T); byte[] bytes = null; var label = "ZeroFormatter." + original.GetType().Name; using (new Measure(label)) { for (int i = 0; i < Iteration; i++) { bytes = ZeroFormatterSerializer.Serialize(original); } } //using (new Measure("Deserialize")) //{ // for (int i = 0; i < Iteration; i++) // { // copy = ZeroFormatterSerializer.Deserialize<T>(bytes); // } //} //if (!dryRun) //{ // Console.WriteLine(string.Format("{0,15} {1}", "Binary Size", ToHumanReadableSize(bytes.Length))); //} return(copy); }
private void SerializeZeroFormatter() { var bytes = ZeroFormatterSerializer.Serialize(Value); RunTest("ZeroFormatter", () => { ZeroFormatterSerializer.Serialize(Value); }, () => { ZeroFormatterSerializer.Deserialize <T>(bytes); }, bytes.Length); }
void PackAndUnpack(MonsterDataBase data) { byte[] bytes = ZeroFormatterSerializer.Serialize <MonsterDataBase>(data); MonsterDataBase loadData = ZeroFormatterSerializer.Deserialize <MonsterDataBase>(bytes); OutputToLog(loadData); }
public void StringUnion() { { var a = new MyA { Age = 9999 }; var data = ZeroFormatterSerializer.Serialize <MyUnion>(a); var union = ZeroFormatterSerializer.Deserialize <MyUnion>(data); union.Key.Is("takotako"); (union as MyA).Age.Is(9999); } { var b = new MyB { Name = "nano" }; var data = ZeroFormatterSerializer.Serialize <MyUnion>(b); var union = ZeroFormatterSerializer.Deserialize <MyUnion>(data); union.Key.Is("hogehoge"); (union as MyB).Name.Is("nano"); } }
private void SaveMetaInfStorage(MetaInfDataStorage meta) { _fileStream.Seek(-GetCalculateMetaInfDataStorageSize(), SeekOrigin.End); ZeroFormatterSerializer.Serialize(_fileStream, meta); metaInfDataStorage = LoadMetaInfStorage(); writeCount++; }
/// <summary> /// Creates a new file, converts the value to binary, writes the contents to the file, and then closes the file. /// If the target file already exists, it is overwritten. /// </summary> /// <param name="fileLocation"></param> /// <param name="value">The object to convert to binary.</param> /// <param name="compressionType">The type of compression to use.</param> public static async Task WriteAsync <T>(string fileLocation, T value, CompressionType compressionType) { Utility.UpdateExtension(ref fileLocation, FileType.Binary); var bytes = ZeroFormatterSerializer.Serialize(value); await Text.WriteAsync(fileLocation, bytes, compressionType).ConfigureAwait(false); }
public async Task SendRoomDataToGameServerAsync(BattleRoyaleMatchModel model) { if (string.IsNullOrEmpty(model.GameServerIp)) { throw new Exception("При отправке данных на игровой сервер ip не указан"); } string serverIp = $"http://{model.GameServerIp}:{Globals.DefaultGameServerHttpPort}"; byte[] roomData = ZeroFormatterSerializer.Serialize(model); Console.WriteLine($"Отправка данных на игровой сервер по ip = {serverIp} количество байт = {roomData.Length}"); HttpContent content = new ByteArrayContent(roomData); var response = await httpClient.PostAsync(serverIp, content); if (response.StatusCode == HttpStatusCode.OK) { Console.WriteLine("Получен ответ от игрового сервера. Статус = \"успешно\" "); byte[] responseData = await response.Content.ReadAsByteArrayAsync(); var r = ZeroFormatterSerializer.Deserialize <GameRoomValidationResult>(responseData); Console.WriteLine($"ResultEnum = {r.ResultEnum}"); } else { //TODO убрать после тестирования throw new Exception($"Брошено исключение при отправке запроса игровому серверу. " + $"Код = {response.StatusCode}"); } }
public void ZeroFormatterSerializeArray() { for (int i = 0; i < Iteration; i++) { ZeroFormatterSerializer.Serialize(l); } }
public static string SerializeToBase64String <T>(this T zeroFormattable) { byte[] data = ZeroFormatterSerializer.Serialize(zeroFormattable); string base64 = Convert.ToBase64String(data); return(base64); }
public static void ExportExceptionInformation(Exception exception, ExceptionInfo exceptionInfo, bool serializeInnerException = true) { var stackTrace = exception.StackTrace; exceptionInfo.Message = MessageField == null ? exception.Message : (string)MessageField.GetValue(exception); exceptionInfo.StackTrace = stackTrace; exceptionInfo.HResult = exception.HResult; exceptionInfo.Source = exception.Source; #if ZEROFORMATTER if (serializeInnerException && exception.InnerException != null) { exceptionInfo.InnerException = ZeroFormatterSerializer.Serialize(PackException(exception.InnerException)); } #endif #if NETSERIALIZER if (serializeInnerException && exception.InnerException != null) { using (var memoryStream = new MemoryStream()) { ExceptionInfo.ExceptionWrapperSerializer.Serialize(memoryStream, PackException(exception.InnerException)); exceptionInfo.InnerException = memoryStream.ToArray(); } } #endif }
public void ZeroFormatterSerializeSingle() { for (int i = 0; i < Iteration; i++) { ZeroFormatterSerializer.Serialize(p); } }
public IEnumerable <string> Get() { var p1 = new YogaPose() { PoseId = 123456789, PoseName = "pose1" }; var p2 = new YogaPose() { PoseId = 123456799, PoseName = "pose2" }; var p3 = new YogaPose() { PoseId = 12346799, PoseName = "pose3" }; List <YogaPose> yogList = new List <YogaPose>(); yogList.Add(p1); yogList.Add(p2); yogList.Add(p3); var bytes = ZeroFormatterSerializer.Serialize(yogList); var myJson = System.Text.Encoding.UTF8.GetString(bytes); return(new string[] { "value1", "value2" }); }
public void Empty() { { IDictionary <long, bool> dict = new Dictionary <long, bool>(); var bytes = ZeroFormatterSerializer.Serialize(dict); var d = ZeroFormatterSerializer.Deserialize <IDictionary <long, bool> >(bytes); d.IsEmpty(); } { var lookup = Enumerable.Empty <int>().ToLookup(x => x % 2 == 0); var c = ZeroFormatterSerializer.Convert(lookup); c.IsEmpty(); } { IList <int> fixedList = Enumerable.Empty <int>().ToArray(); var c = ZeroFormatterSerializer.Convert(fixedList); c.IsEmpty(); } { IList <string> variableList = Enumerable.Empty <string>().ToArray(); var c = ZeroFormatterSerializer.Convert(variableList); c.IsEmpty(); } }
private async Task <ShopModel> InitProductCostAsync(ShopModel shopModel) { log.Debug($"Ожидание инициализации {nameof(purchasingService)}"); List <RealCurrencyCostModel> realCurrencyProducts = shopModel.GetRealCurrencyProducts(); purchasingService.StartInitialization(realCurrencyProducts); await MyTaskExtensions.WaitUntil(purchasingService.IsStoreInitialized); log.Debug($"{nameof(purchasingService)} инициализирован"); foreach (ProductModel productModel in shopModel.GetAllProducts()) { if (productModel.CostModel.CostTypeEnum == CostTypeEnum.RealCurrency) { var realCurrencyCostModel = ZeroFormatterSerializer .Deserialize <RealCurrencyCostModel>(productModel.CostModel.SerializedCostModel); string productId = realCurrencyCostModel.GoogleProductId; string cost = null; purchasingService.TryGetProductCostById(productId, ref cost); if (cost == null) { throw new Exception("Не удалось достать цену товара из плагина магазина"); } realCurrencyCostModel.CostString = cost; productModel.CostModel.SerializedCostModel = ZeroFormatterSerializer.Serialize(realCurrencyCostModel); } } return(shopModel); }
public override byte[] SerializeState() { return(ZeroFormatterSerializer.Serialize(new FlyingBlockServerState { Block = PresentedBlock, Age = Age, ContactAction = ContactAction, MaxAge = MaxAge, MoveDirection = Mover.Velocity })); }
public byte[] GetSerializedMessage <T>(T message, bool rudpEnabled, int matchId, ushort playerId, out uint messageId) where T : ITypedMessage { MessageWrapper messageWrapper = GetMessage(message, rudpEnabled, matchId, playerId, out messageId); return(ZeroFormatterSerializer.Serialize(messageWrapper)); }
private static uint getSizeOfConsumerRecord() { var record = new ConsumerRecord(); var result = ZeroFormatterSerializer.Serialize(record); return((uint)result.Length); }
public void String() { { // japanese-hiragana and surrogate pair kanji and emoji. var r = ZeroFormatterSerializer.Serialize("あいうえお𠮷野家😀💓"); ZeroFormatterSerializer.Deserialize <string>(r).Is("あいうえお𠮷野家😀💓"); } { var r = ZeroFormatterSerializer.Serialize <string>(null); ZeroFormatterSerializer.Deserialize <string>(r).IsNull(); } { var f = Formatters.Formatter <DefaultResolver, string> .Default; byte[] b = null; var size = f.Serialize(ref b, 0, "aiueo"); b.Length.Is(size); // just size int size2; f.Deserialize(ref b, 0, DirtyTracker.NullTracker, out size2).Is("aiueo"); } { var f = Formatters.Formatter <DefaultResolver, string> .Default; byte[] b = new byte[20]; var size = f.Serialize(ref b, 5, "aiueo"); b.Length.IsNot(size); // not just size int size2; f.Deserialize(ref b, 5, DirtyTracker.NullTracker, out size2).Is("aiueo"); } }
public void VariableReadOnlyList() { var bytes = new byte[1000]; IReadOnlyList <string> variableList = new[] { "abcde", "fghijk" }; var record = KeyTuple.Create("aiueo", variableList, "kakikukeko"); var size = ZeroFormatterSerializer.Serialize(ref bytes, 33, record); var newBytes = new byte[2000]; Buffer.BlockCopy(bytes, 33, newBytes, 99, size); var result = ZeroFormatterSerializer.Deserialize <KeyTuple <string, IList <string>, string> >(newBytes, 99); { result.Item1.Is("aiueo"); var l = result.Item2; l.Count.Is(2); l[0].Is("abcde"); l[1].Is("fghijk"); result.Item3.Is("kakikukeko"); } result.Item2[0] = "zzzzz"; // mutate var reconvert = ZeroFormatterSerializer.Convert(result); { reconvert.Item1.Is("aiueo"); var l = reconvert.Item2; l.Count.Is(2); l[0].Is("zzzzz"); l[1].Is("fghijk"); reconvert.Item3.Is("kakikukeko"); } }
public ProductModel Create(int amount, string imagePath, string productGoogleId) { return(new ProductModel { ResourceTypeEnum = ResourceTypeEnum.HardCurrency, CostModel = new CostModel() { CostTypeEnum = CostTypeEnum.RealCurrency, SerializedCostModel = ZeroFormatterSerializer.Serialize(new RealCurrencyCostModel() { IsConsumable = true, AppleProductId = null, GoogleProductId = productGoogleId, CostString = null }) }, IsDisabled = false, SerializedModel = ZeroFormatterSerializer.Serialize(new HardCurrencyProductModel() { Amount = amount }), PreviewImagePath = imagePath, ProductSizeEnum = ProductSizeEnum.Small }); }
public static void DoExperiment2() { var d = generateSimpleExperimentData(); var formatter = new BinaryFormatter(); var bytes = ZeroFormatterSerializer.Serialize(d); var dataSize = bytes.Length; var queueSize = dataSize * 50; using (var file = MemoryMappedFile.CreateOrOpen("testFile-headers", dataSize)) { var viewStream = file.CreateViewStream(0, dataSize); viewStream.Write(bytes, 0, dataSize); viewStream.Close(); var newViewStream = file.CreateViewStream(0, dataSize); var result = ZeroFormatterSerializer.Deserialize <ExperimentMessageType>(newViewStream); newViewStream.Close(); var convertedResult = (ExperimentMessageType)result; Console.WriteLine($"a:{d.name}, b:{convertedResult.name}"); } }
static T SerializeZeroFormatter <T>(T original) { Console.WriteLine("ZeroFormatter"); T copy = default(T); byte[] bytes = null; using (new Measure("Serialize")) { for (int i = 0; i < Iteration; i++) { bytes = ZeroFormatterSerializer.Serialize(original); } } using (new Measure("Deserialize")) { for (int i = 0; i < Iteration; i++) { copy = ZeroFormatterSerializer.Deserialize <T>(bytes); } } if (!dryRun) { Console.WriteLine(string.Format("{0,15} {1}", "Binary Size", ToHumanReadableSize(bytes.Length))); } return(copy); }
public void IncludeWithFallback() { var huga = new Sandbox.Shared.IStandardUnion[] { (Sandbox.Shared.IStandardUnion) new Sandbox.Shared.MessageA1(), (Sandbox.Shared.IStandardUnion) new Sandbox.Shared.MessageB1(), (Sandbox.Shared.IStandardUnion) new Sandbox.Shared.MessageA1(), (Sandbox.Shared.IStandardUnion) new Sandbox.Shared.MessageB1(), }; var ninon = ZeroFormatterSerializer.Serialize(huga); var hoge = ZeroFormatterSerializer.Deserialize <Sandbox.Shared.IStandardUnion[]>(ninon); hoge[0].IsInstanceOf <Sandbox.Shared.MessageA1>(); hoge[1].IsInstanceOf <Sandbox.Shared.MessageB1>(); hoge[2].IsInstanceOf <Sandbox.Shared.MessageA1>(); hoge[3].IsInstanceOf <Sandbox.Shared.MessageB1>(); Internal.BinaryUtil.WriteInt32(ref ninon, 28, 212); var hoge2 = ZeroFormatterSerializer.Deserialize <Sandbox.Shared.IStandardUnion[]>(ninon); hoge2[0].IsInstanceOf <Sandbox.Shared.MessageA1>(); hoge2[1].IsInstanceOf <Sandbox.Shared.UnknownMessage1>(); hoge2[2].IsInstanceOf <Sandbox.Shared.MessageA1>(); hoge2[3].IsInstanceOf <Sandbox.Shared.MessageB1>(); }
public void String() { var _ = ZeroFormatterSerializer.Serialize <string>(""); var str = ZeroFormatterSerializer.Deserialize <string>(_); var ms = new MemoryStream(); var bw = new BinaryWriter(ms); bw.Write(Encoding.UTF8.GetByteCount("あいうえおかきくけこさしすえそなにぬねの")); bw.Write("あいうえおかきくけこさしすえそなにぬねの"); var actual = ms.ToArray(); var tracker = new DirtyTracker(); tracker.IsDirty.IsFalse(); var segment = new CacheSegment <DefaultResolver, string>(tracker, new ArraySegment <byte>(actual)); segment.Value = "あいうえおかきくけこ"; tracker.IsDirty.IsTrue(); byte[] result = new byte[0]; segment.Serialize(ref result, 0); ZeroFormatterSerializer.Deserialize <string>(result).Is("あいうえおかきくけこ"); segment.Value = null; segment.Serialize(ref result, 0); ZeroFormatterSerializer.Deserialize <string>(result).IsNull(); }
public void Write() { File.WriteAllBytes(UserDataFilePath, ZeroFormatterSerializer.Serialize(UserData)); File.WriteAllBytes(PuzzleDataFilePath, ZeroFormatterSerializer.Serialize(PuzzleData)); ReplayData.Version = 0; File.WriteAllBytes(ReplayDataFilePath, ZeroFormatterSerializer.Serialize(ReplayData)); }
public void NullCheck() { // Segment: var bytes = ZeroFormatterSerializer.Serialize <IDictionary <int, int> >(null); ZeroFormatterSerializer.Deserialize <IDictionary <int, int> >(bytes).IsNull(); bytes = ZeroFormatterSerializer.Serialize <IList <int> >(null); ZeroFormatterSerializer.Deserialize <IList <int> >(bytes).IsNull(); bytes = ZeroFormatterSerializer.Serialize <IList <string> >(null); ZeroFormatterSerializer.Deserialize <IList <string> >(bytes).IsNull(); bytes = ZeroFormatterSerializer.Serialize <ILookup <int, int> >(null); ZeroFormatterSerializer.Deserialize <ILookup <int, int> >(bytes).IsNull(); bytes = ZeroFormatterSerializer.Serialize <MyFormatClass>(null); ZeroFormatterSerializer.Deserialize <MyFormatClass>(bytes).IsNull(); bytes = ZeroFormatterSerializer.Serialize <byte[]>(null); ZeroFormatterSerializer.Deserialize <byte[]>(bytes).IsNull(); bytes = ZeroFormatterSerializer.Serialize <string>(null); ZeroFormatterSerializer.Deserialize <string>(bytes).IsNull(); }
private void SerializeZeroFormatterWithPooling() { var bytes = ZeroFormatterSerializer.Serialize(Value); RunTest("ZeroFormatterWithPooling", () => { ZeroFormatterSerializer.Serialize(ref bytes, 0, Value); }, () => { ZeroFormatterSerializer.Deserialize <T>(bytes); }, bytes.Length); }
public void LookupSegment() { var lookup = Enumerable.Range(1, 10) .ToLookup(x => x % 2 == 0); var bytes = ZeroFormatterSerializer.Serialize(lookup); int _; var segment = LookupSegment <bool, int> .Create(new DirtyTracker(0), bytes, 0, LookupSegmentMode.Immediate, out _); segment[true].Is(2, 4, 6, 8, 10); segment[false].Is(1, 3, 5, 7, 9); bool isFirst = true; foreach (var g in segment.OrderByDescending(x => x.Key)) { if (isFirst) { isFirst = false; g.Key.IsTrue(); g.AsEnumerable().Is(2, 4, 6, 8, 10); } else { g.Key.IsFalse(); g.AsEnumerable().Is(1, 3, 5, 7, 9); } } }
public void FixedList() { { IList <int> xs = new[] { 12, 431, 426, 76, 373, 7, 53, 563, 563 }; var result = ZeroFormatterSerializer.Serialize(xs); ZeroFormatterSerializer.Deserialize <IList <int> >(result).Is(12, 431, 426, 76, 373, 7, 53, 563, 563); } { IList <int?> xs = new int?[] { 12, 431, 426, null, 76, 373, 7, 53, 563, 563 }; var result = ZeroFormatterSerializer.Serialize(xs); ZeroFormatterSerializer.Deserialize <IList <int?> >(result).Is(12, 431, 426, null, 76, 373, 7, 53, 563, 563); } { IList <double> xs = new[] { 12.32, 43.1, 4.26, 76, 0.373, 7.3, 0.53, 56.3, 5.63 }; var result = ZeroFormatterSerializer.Serialize(xs); ZeroFormatterSerializer.Deserialize <IList <double> >(result).Is(12.32, 43.1, 4.26, 76, 0.373, 7.3, 0.53, 56.3, 5.63); } { IList <double?> xs = new double?[] { 12.32, 43.1, 4.26, 76, 0.373, 7.3, null, 0.53, 56.3, null, 5.63 }; var result = ZeroFormatterSerializer.Serialize(xs); ZeroFormatterSerializer.Deserialize <IList <double?> >(result).Is(12.32, 43.1, 4.26, 76, 0.373, 7.3, null, 0.53, 56.3, null, 5.63); } { IList <int> xs = new int[0]; var result = ZeroFormatterSerializer.Serialize(xs); ZeroFormatterSerializer.Deserialize <IList <int> >(result).IsZero(); } }
public byte[] GetPosUpdateMessage(out PosUpdateType type) { var p = NeedSyncPosition; var r = NeedSyncRotation; type = PosUpdateType.None; if (p && r) { type = PosUpdateType.PosRot; var c = new S_UpdateEntityPosRotMessage { CommandID = (byte)PosUpdateType.PosRot, Position = Position, Rotation = PackedRotation, UID = _owner.UID }; return(ZeroFormatterSerializer.Serialize(c)); } if (p) { type = PosUpdateType.Pos; var c = new S_UpdateEntityPosMessage { CommandID = (byte)PosUpdateType.Pos, Position = Position, UID = _owner.UID }; return(ZeroFormatterSerializer.Serialize(c)); } if (r) { type = PosUpdateType.Rot; var c = new S_UpdateEntityRotMessage { CommandID = (byte)PosUpdateType.Rot, Rotation = PackedRotation, UID = _owner.UID }; return(ZeroFormatterSerializer.Serialize(c)); } return(null); }