Skip to content

Commit

Permalink
feat(Cid): supporting byte arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
richardschneider committed Nov 25, 2018
1 parent 8d13438 commit a28ab22
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/Cid.cs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,38 @@ public void Write(CodedOutputStream stream)
}
}

/// <summary>
/// Reads the binary representation of the CID from the specified byte array.
/// </summary>
/// <param name="buffer">
/// The souce of a CID.
/// </param>
/// <returns>
/// A new <see cref="Cid"/>.
/// </returns>
public static Cid Read(byte[] buffer)
{
using (var ms = new MemoryStream(buffer, false))
{
return Read(ms);
}
}

/// <summary>
/// Returns the binary representation of the CID as a byte array.
/// </summary>
/// <returns>
/// A new buffer containing the CID>
/// </returns>
public byte[] ToArray()
{
using (var ms = new MemoryStream())
{
Write(ms);
return ms.ToArray();
}
}

/// <summary>
/// Implicit casting of a <see cref="MultiHash"/> to a <see cref="Cid"/>.
/// </summary>
Expand Down
12 changes: 12 additions & 0 deletions test/CidTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -393,5 +393,17 @@ public void JsonSerialization()
Assert.AreEqual(x.Cid, y.Cid);
Assert.AreEqual(x.X, y.X);
}

[TestMethod]
public void ByteArrays()
{
Cid cid = "zBunRGrmCGokA1oMESGGTfrtcMFsVA8aEtcNzM54akPWXF97uXCqTjF3GZ9v8YzxHrG66J8QhtPFWwZebRZ2zeUEELu67";
var buffer = cid.ToArray();
var clone = Cid.Read(buffer);
Assert.AreEqual(cid.Version, clone.Version);
Assert.AreEqual(cid.ContentType, clone.ContentType);
Assert.AreEqual(cid.Hash.Algorithm.Name, clone.Hash.Algorithm.Name);
Assert.AreEqual(cid.Hash, clone.Hash);
}
}
}

0 comments on commit a28ab22

Please sign in to comment.