Skip to content

Commit

Permalink
Merge pull request #937 from xPaw/patch-1
Browse files Browse the repository at this point in the history
Write empty values (null and no children) as an object when saving to binary
  • Loading branch information
yaakov-h authored Nov 16, 2020
2 parents 9e47eab + 313ef90 commit 641b55b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
4 changes: 2 additions & 2 deletions SteamKit2/SteamKit2/Types/KeyValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -733,7 +733,7 @@ void RecursiveSaveBinaryToStreamCore( Stream f )
// Only supported types ATM:
// 1. KeyValue with children (no value itself)
// 2. String KeyValue
if ( Children.Any() )
if ( Value == null )
{
f.WriteByte( ( byte )Type.None );
f.WriteNullTermString( GetNameForSerialization(), Encoding.UTF8 );
Expand All @@ -747,7 +747,7 @@ void RecursiveSaveBinaryToStreamCore( Stream f )
{
f.WriteByte( ( byte )Type.String );
f.WriteNullTermString( GetNameForSerialization(), Encoding.UTF8 );
f.WriteNullTermString( Value ?? string.Empty, Encoding.UTF8 );
f.WriteNullTermString( Value, Encoding.UTF8 );
}
}

Expand Down
49 changes: 49 additions & 0 deletions SteamKit2/Tests/KeyValueFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,55 @@ public void KeyValuesEscapesTextWhenSerializing()
Assert.Equal( expectedValue, text );
}

[Fact]
public void KeyValuesTextPreserveEmptyObjects()
{
var kv = new KeyValue( "key" );
kv.Children.Add( new KeyValue( "emptyObj" ) );
kv.Children.Add( new KeyValue( "emptyString", string.Empty ) );

string text;
using ( var ms = new MemoryStream() )
{
kv.SaveToStream( ms, asBinary: false );
ms.Seek( 0, SeekOrigin.Begin );
using ( var reader = new StreamReader( ms ) )
{
text = reader.ReadToEnd();
}
}

var expectedValue = "\"key\"\n{\n\t\"emptyObj\"\n\t{\n\t}\n\t\"emptyString\"\t\t\"\"\n}\n";
Assert.Equal( expectedValue, text );
}

[Fact]
public void KeyValuesBinaryPreserveEmptyObjects()
{
var expectedHexString = "006B65790000656D7074794F626A000801656D707479537472696E6700000808";

var kv = new KeyValue( "key" );
kv.Children.Add( new KeyValue( "emptyObj" ) );
kv.Children.Add( new KeyValue( "emptyString", string.Empty ) );

var deserializedKv = new KeyValue();
byte[] binaryValue;
using ( var ms = new MemoryStream() )
{
kv.SaveToStream( ms, asBinary: true );
ms.Seek( 0, SeekOrigin.Begin );
binaryValue = ms.ToArray();
deserializedKv.TryReadAsBinary( ms );
}

var hexValue = BitConverter.ToString( binaryValue ).Replace( "-", "" );

Assert.Equal( expectedHexString, hexValue );
Assert.Null( deserializedKv["emptyObj"].Value );
Assert.Empty( deserializedKv["emptyObj"].Children );
Assert.Equal( string.Empty, deserializedKv["emptyString"].Value );
}

[Fact]
public void DecodesBinaryWithFieldType10()
{
Expand Down

0 comments on commit 641b55b

Please sign in to comment.