Skip to content

Commit

Permalink
feat(MultiAddress): try to create or return null
Browse files Browse the repository at this point in the history
  • Loading branch information
richardschneider committed Sep 6, 2018
1 parent bc5ab7a commit aea9d67
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/MultiAddress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Ipfs
/// A multi address is considered immutablle and value type equality is implemented.
/// </para>
/// </remarks>
/// <seealso href="https://github.com/jbenet/multiaddr"/>
/// <seealso href="https://github.com/multiformats/multiaddr"/>
public class MultiAddress : IEquatable<MultiAddress>
{
/// <summary>
Expand Down Expand Up @@ -357,7 +357,27 @@ static public implicit operator MultiAddress(string s)
return new MultiAddress(s);
}


/// <summary>
/// Try to create a <see cref="MultiAddress"/> from the specified
/// string.
/// </summary>
/// <param name="s">
/// The string representation of a multi address, such as "/ip4/1270.0.01/tcp/5001".
/// </param>
/// <returns>
/// <b>null</b> if the string cannot be parsed; otherwise a <see cref="MultiAddress"/>.
/// </returns>
public static MultiAddress TryCreate(string s)
{
try
{
return new MultiAddress(s);
}
catch
{
return null;
}
}

}

Expand Down
3 changes: 3 additions & 0 deletions src/NetworkProtocol.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ namespace Ipfs
/// <summary>
/// Metadata on an IPFS network address protocol.
/// </summary>
/// <remarks>
/// Protocols are defined at <see href="https://github.com/multiformats/multiaddr/blob/master/protocols.csv"/>.
/// </remarks>
/// <seealso cref="MultiAddress"/>
public abstract class NetworkProtocol
{
Expand Down
10 changes: 10 additions & 0 deletions test/MultiAddressTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,16 @@ public void Ipv6ScopeId_Ignored()
Assert.AreEqual(ma2, ma1);
Assert.AreEqual(ma2.ToString(), ma1.ToString());
}

[TestMethod]
public void TryCreate()
{
Assert.IsNotNull(MultiAddress.TryCreate("/ip4/1.2.3.4/tcp/80"));
Assert.IsNull(MultiAddress.TryCreate(null));
Assert.IsNull(MultiAddress.TryCreate(" "));
Assert.IsNull(MultiAddress.TryCreate("/tcp/alpha")); // bad port
Assert.IsNull(MultiAddress.TryCreate("/foobar")); // bad protocol
}
}
}

0 comments on commit aea9d67

Please sign in to comment.