From fff2fc60983235889d8fe16482f8592d0a0afe17 Mon Sep 17 00:00:00 2001 From: Garry Newman Date: Mon, 13 May 2019 20:05:10 +0100 Subject: [PATCH] Cleaning up inventory deserialize --- Facepunch.Steamworks.Test/InventoryTest.cs | 45 ++++++++++++++++++++++ Facepunch.Steamworks/SteamInventory.cs | 26 ++++++------- 2 files changed, 58 insertions(+), 13 deletions(-) diff --git a/Facepunch.Steamworks.Test/InventoryTest.cs b/Facepunch.Steamworks.Test/InventoryTest.cs index fd7bec2..fff40a3 100644 --- a/Facepunch.Steamworks.Test/InventoryTest.cs +++ b/Facepunch.Steamworks.Test/InventoryTest.cs @@ -146,6 +146,51 @@ namespace Steamworks } } } + + [TestMethod] + public async Task Serialize() + { + await SteamInventory.WaitForDefinitions(); + + var result = await SteamInventory.GetAllItemsAsync(); + + Assert.IsTrue( result.HasValue ); + + var data = result.Value.Serialize(); + + Assert.IsNotNull( data ); + + Console.WriteLine( string.Join( "", data.Select( x => x.ToString( "x" ) ) ) ); + } + + [TestMethod] + public async Task Deserialize() + { + await SteamInventory.WaitForDefinitions(); + + byte[] data = null; + int itemCount = 0; + + // Serialize + { + var result = await SteamInventory.GetAllItemsAsync(); + Assert.IsTrue( result.HasValue ); + itemCount = result.Value.ItemCount; + data = result.Value.Serialize(); + Assert.IsNotNull( data ); + result.Value.Dispose(); + } + + await Task.Delay( 2000 ); + + // Deserialize + { + var result = await SteamInventory.DeserializeAsync( data ); + Assert.IsTrue( result.HasValue ); + Assert.AreEqual( itemCount, result.Value.ItemCount ); + result.Value.Dispose(); + } + } } } diff --git a/Facepunch.Steamworks/SteamInventory.cs b/Facepunch.Steamworks/SteamInventory.cs index 21ab944..24cb978 100644 --- a/Facepunch.Steamworks/SteamInventory.cs +++ b/Facepunch.Steamworks/SteamInventory.cs @@ -280,28 +280,28 @@ namespace Steamworks public static async Task DeserializeAsync( byte[] data, int dataLength = -1 ) { if ( data == null ) - throw new ArgumentException( "data should nto be null" ); + throw new ArgumentException( "data should not be null" ); if ( dataLength == -1 ) dataLength = data.Length; - var sresult = DeserializeResult( data, dataLength ); - if ( !sresult.HasValue ) return null; + var ptr = Marshal.AllocHGlobal( dataLength ); - return await InventoryResult.GetAsync( sresult.Value ); - } - - internal static unsafe SteamInventoryResult_t? DeserializeResult( byte[] data, int dataLength = -1 ) - { - var sresult = default( SteamInventoryResult_t ); - - fixed ( byte* ptr = data ) + try { + Marshal.Copy( data, 0, ptr, dataLength ); + + var sresult = default( SteamInventoryResult_t ); + if ( !Internal.DeserializeResult( ref sresult, (IntPtr)ptr, (uint)dataLength, false ) ) return null; - } - return sresult; + return await InventoryResult.GetAsync( sresult.Value ); + } + finally + { + Marshal.FreeHGlobal( ptr ); + } }