Skip to content

Commit

Permalink
fix(Cid): Cid byte arrays do NOT contain a length prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
richardschneider committed Nov 27, 2018
1 parent a28ab22 commit 87b692f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
28 changes: 25 additions & 3 deletions src/Cid.cs
Original file line number Diff line number Diff line change
Expand Up @@ -387,25 +387,47 @@ public void Write(CodedOutputStream stream)
/// <returns>
/// A new <see cref="Cid"/>.
/// </returns>
/// <remarks>
/// The buffer does NOT start with a varint length prefix.
/// </remarks>
public static Cid Read(byte[] buffer)
{
var cid = new Cid();
if (buffer.Length == 34)
{
cid.Version = 0;
cid.Hash = new MultiHash(buffer);
return cid;
}

using (var ms = new MemoryStream(buffer, false))
{
return Read(ms);
cid.Version = ms.ReadVarint32();
cid.ContentType = ms.ReadMultiCodec().Name;
cid.Hash = new MultiHash(ms);
return cid;
}
}

/// <summary>
/// Returns the binary representation of the CID as a byte array.
/// </summary>
/// <returns>
/// A new buffer containing the CID>
/// A new buffer containing the CID.
/// </returns>
/// <remarks>
/// The buffer does NOT start with a varint length prefix.
/// </remarks>
public byte[] ToArray()
{
if (Version == 0)
return Hash.ToArray();

using (var ms = new MemoryStream())
{
Write(ms);
ms.WriteVarint(Version);
ms.WriteMultiCodec(this.ContentType);
Hash.Write(ms);
return ms.ToArray();
}
}
Expand Down
15 changes: 14 additions & 1 deletion test/CidTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ public void JsonSerialization()
}

[TestMethod]
public void ByteArrays()
public void ByteArrays_V1()
{
Cid cid = "zBunRGrmCGokA1oMESGGTfrtcMFsVA8aEtcNzM54akPWXF97uXCqTjF3GZ9v8YzxHrG66J8QhtPFWwZebRZ2zeUEELu67";
var buffer = cid.ToArray();
Expand All @@ -405,5 +405,18 @@ public void ByteArrays()
Assert.AreEqual(cid.Hash.Algorithm.Name, clone.Hash.Algorithm.Name);
Assert.AreEqual(cid.Hash, clone.Hash);
}

[TestMethod]
public void ByteArrays_V0()
{
var buffer = "1220a4edf38611d7d4a2d3ff2d97f88a7256eba31b57982f803b4de7bbeb0343c37b".ToHexBuffer();
var cid = Cid.Read(buffer);
Assert.AreEqual(0, cid.Version);
Assert.AreEqual("dag-pb", cid.ContentType);
Assert.AreEqual("QmZSU1xNFsBtCnzK2Nk9N4bAxQiVNdmugU9DQDE3ntkTpe", cid.Hash.ToString());

var clone = cid.ToArray();
CollectionAssert.AreEqual(buffer, clone);
}
}
}

0 comments on commit 87b692f

Please sign in to comment.