Commit 190a936b authored by kevin-montrose's avatar kevin-montrose

add TryParse() methods to Redis.Value for common conversion; exposing publicly...

add TryParse() methods to Redis.Value for common conversion; exposing publicly functions already available internally
parent d994b7ad
...@@ -161,5 +161,52 @@ public void CanBeDynamic() ...@@ -161,5 +161,52 @@ public void CanBeDynamic()
Assert.AreEqual((byte)'b', blob[1]); Assert.AreEqual((byte)'b', blob[1]);
Assert.AreEqual((byte)'c', blob[2]); Assert.AreEqual((byte)'c', blob[2]);
} }
[Test]
public void TryParse()
{
{
RedisValue val = "1";
int i;
Assert.IsTrue(val.TryParse(out i));
Assert.AreEqual(1, i);
long l;
Assert.IsTrue(val.TryParse(out l));
Assert.AreEqual(1L, l);
double d;
Assert.IsTrue(val.TryParse(out d));
Assert.AreEqual(1.0, l);
}
{
RedisValue val = "8675309";
int i;
Assert.IsTrue(val.TryParse(out i));
Assert.AreEqual(8675309, i);
long l;
Assert.IsTrue(val.TryParse(out l));
Assert.AreEqual(8675309L, l);
double d;
Assert.IsTrue(val.TryParse(out d));
Assert.AreEqual(8675309.0, l);
}
{
RedisValue val = "3.14159";
double d;
Assert.IsTrue(val.TryParse(out d));
Assert.AreEqual(3.14159, d);
}
{
RedisValue val = "not a real number";
int i;
Assert.IsFalse(val.TryParse(out i));
long l;
Assert.IsFalse(val.TryParse(out l));
double d;
Assert.IsFalse(val.TryParse(out d));
}
}
} }
} }
...@@ -637,6 +637,71 @@ uint IConvertible.ToUInt32(IFormatProvider provider) ...@@ -637,6 +637,71 @@ uint IConvertible.ToUInt32(IFormatProvider provider)
ulong IConvertible.ToUInt64(IFormatProvider provider) ulong IConvertible.ToUInt64(IFormatProvider provider)
{ {
return (ulong)this; return (ulong)this;
}
/// <summary>
/// Convert to a long if possible, returning true.
///
/// Returns false otherwise.
/// </summary>
public bool TryParse(out long val)
{
var blob = valueBlob;
if (blob == IntegerSentinel)
{
val = valueInt64;
return true;
}
if (blob == null)
{
// in redis-land 0 approx. equal null; so roll with it
val = 0;
return true;
}
return TryParseInt64(blob, 0, blob.Length, out val);
}
/// <summary>
/// Convert to a int if possible, returning true.
///
/// Returns false otherwise.
/// </summary>
public bool TryParse(out int val)
{
long l;
if (!TryParse(out l) || l > int.MaxValue || l < int.MinValue)
{
val = 0;
return false;
}
val = (int)l;
return true;
}
/// <summary>
/// Convert to a double if possible, returning true.
///
/// Returns false otherwise.
/// </summary>
public bool TryParse(out double val)
{
var blob = valueBlob;
if (blob == IntegerSentinel)
{
val = valueInt64;
return true;
}
if (blob == null)
{
// in redis-land 0 approx. equal null; so roll with it
val = 0;
return true;
}
return TryParseDouble(blob, out val);
} }
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment