public void Serialize() { var buffer = new byte[1024]; var random = new Random(); byte[] hash = random.NextBytes(20); var f = new Fingerprint(ValueKind.List, 123, hash); Assert.Equal( new Fingerprint(ValueKind.List, 123, hash.ToImmutableList()).Serialize(), f.Serialize() ); Assert.Equal(f, Fingerprint.Deserialize(f.Serialize())); long estimatedSize = f.CountSerializationBytes(); Assert.Equal(f.Serialize().LongLength, estimatedSize); long writtenSize = f.SerializeInto(buffer, 128L); Assert.Equal(estimatedSize, writtenSize); AssertEqual(f.Serialize(), buffer.Skip(128).Take((int)writtenSize).ToArray()); Assert.Equal(f, Fingerprint.Deserialize(buffer, 128L, writtenSize)); var s = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(s, f); s.Seek(0, SeekOrigin.Begin); Assert.Equal(f, (Fingerprint)formatter.Deserialize(s)); hash = random.NextBytes(20); f = new Fingerprint(ValueKind.Dictionary, 456, hash); Assert.Equal(f, Fingerprint.Deserialize(f.Serialize())); estimatedSize = f.CountSerializationBytes(); Assert.Equal(f.Serialize().LongLength, estimatedSize); writtenSize = f.SerializeInto(buffer, 512L); Assert.Equal(estimatedSize, writtenSize); AssertEqual(f.Serialize(), buffer.Skip(512).Take((int)writtenSize).ToArray()); Assert.Equal(f, Fingerprint.Deserialize(buffer, 512L, writtenSize)); byte[] tooShort = f.Serialize().Take(8).ToArray(); FormatException e = Assert.Throws <FormatException>( () => Fingerprint.Deserialize(tooShort) ); Assert.Contains("too short", e.Message, StringComparison.OrdinalIgnoreCase); byte[] invalidKind = f.Serialize(); invalidKind[0] = byte.MaxValue; e = Assert.Throws <FormatException>( () => Fingerprint.Deserialize(invalidKind) ); Assert.Contains("invalid value kind", e.Message, StringComparison.OrdinalIgnoreCase); s = new MemoryStream(); formatter.Serialize(s, f); s.Seek(0, SeekOrigin.Begin); Assert.Equal(f, (Fingerprint)formatter.Deserialize(s)); }