From d37b651761cefe1da2122232d1f99ee2a7e8ca04 Mon Sep 17 00:00:00 2001 From: UnknownShadow200 Date: Tue, 23 Feb 2016 21:07:26 +1100 Subject: [PATCH] Allocate less memory in SendRawMap. --- Network/Player.Networking.cs | 7 +++--- util/Extensions.cs | 43 +++++++++++++++++++----------------- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/Network/Player.Networking.cs b/Network/Player.Networking.cs index 9ceae3586..3695eef2e 100644 --- a/Network/Player.Networking.cs +++ b/Network/Player.Networking.cs @@ -338,10 +338,11 @@ namespace MCGalaxy { } SendRaw(Opcode.LevelInitialise); - buffer = buffer.GZip(); - int totalRead = 0; + int usedLength = 0; + buffer = buffer.GZip(out usedLength); + int totalRead = 0; - while (totalRead < buffer.Length) { + while (totalRead < usedLength) { byte[] packet = new byte[1028]; // need each packet separate for Mono packet[0] = Opcode.LevelDataChunk; short length = (short)Math.Min(buffer.Length - totalRead, 1024); diff --git a/util/Extensions.cs b/util/Extensions.cs index ffca95f65..560b4f645 100644 --- a/util/Extensions.cs +++ b/util/Extensions.cs @@ -24,33 +24,36 @@ using System.IO.Compression; using System.Linq; using System.Text; using System.Text.RegularExpressions; -namespace MCGalaxy -{ - public static class Extensions - { - public static string Truncate(this string source, int maxLength) - { + +namespace MCGalaxy { + + public static class Extensions { + + public static string Truncate(this string source, int maxLength) { if (source.Length > maxLength) - { source = source.Substring(0, maxLength); - } return source; } - public static byte[] GZip(this byte[] bytes) - { - using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) - { - GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true); - gs.Write(bytes, 0, bytes.Length); - gs.Close(); + + public static byte[] GZip(this byte[] bytes) { + using (MemoryStream ms = new MemoryStream()) { + using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true)) + gs.Write(bytes, 0, bytes.Length); + ms.Position = 0; - bytes = new byte[ms.Length]; - ms.Read(bytes, 0, (int)ms.Length); - ms.Close(); - ms.Dispose(); + return ms.ToArray(); } - return bytes; } + + public static byte[] GZip(this byte[] bytes, out int length) { + using (MemoryStream ms = new MemoryStream()) { + using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true)) + gs.Write(bytes, 0, bytes.Length); + length = (int)ms.Length; + return ms.GetBuffer(); + } + } + public static byte[] Decompress(this byte[] gzip, int capacity = 16) { // Create a GZIP stream with decompression mode.