Commit 9b6d1e73 authored by jacobgladish's avatar jacobgladish

Enhanced CanConvert on Variant.

parent 83e1372f
......@@ -386,8 +386,26 @@ common::Variant::AssignFrom(Variant const& other)
bool
common::Variant::CanConvert(DataType t) const
{
// TODO: better type conversion
return m_data.Type == t;
if (m_data.Type == t)
return true;
bool canConvert = false;
switch (m_data.Type)
{
case DataType::Invalid: break;
case DataType::Boolean: if (!canConvert) canConvert = (t == DataType::Boolean);
case DataType::UInt8: if (!canConvert) canConvert = (t == DataType::UInt8);
case DataType::Int16: if (!canConvert) canConvert = (t == DataType::Int16);
case DataType::UInt16: if (!canConvert) canConvert = (t == DataType::UInt16);
case DataType::Int32: if (!canConvert) canConvert = (t == DataType::Int32);
case DataType::UInt32: if (!canConvert) canConvert = (t == DataType::UInt32);
case DataType::Int64: if (!canConvert) canConvert = (t == DataType::Int64);
case DataType::UInt64: if (!canConvert) canConvert = (t == DataType::UInt64);
break;
default: assert(false);
break;
}
return canConvert;
}
std::string
......
......@@ -116,6 +116,8 @@ namespace common
std::string ToString() const;
bool CanConvert(DataType t) const;
private:
template<class T>
static void* allocArray(int n)
......@@ -131,8 +133,6 @@ namespace common
delete [] arr;
}
bool CanConvert(DataType t) const;
template<class T>
T Convert(DataType t) const
{
......
......@@ -116,6 +116,33 @@ TEST(VariantTest, StringCopyAssign) {
EXPECT_EQ(v1.ToString(), v2.ToString());
}
TEST(Variant, Convert)
{
common::Variant v1( (uint8_t) 12 );
EXPECT_FALSE(v1.CanConvert(common::Variant::DataType::Boolean));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::UInt8));
// maybe extend Variant to do runtime checking. i.e int64_t == 10 is convertable to
// int8_t, etc.
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::UInt16));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::UInt32));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::UInt64));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::Int16));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::Int32));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::Int64));
v1 = (uint32_t) 12345;
EXPECT_FALSE(v1.CanConvert(common::Variant::DataType::Boolean));
EXPECT_FALSE(v1.CanConvert(common::Variant::DataType::UInt8));
EXPECT_FALSE(v1.CanConvert(common::Variant::DataType::UInt16));
EXPECT_FALSE(v1.CanConvert(common::Variant::DataType::Int16));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::UInt32));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::UInt64));
EXPECT_FALSE(v1.CanConvert(common::Variant::DataType::Int32));
EXPECT_TRUE(v1.CanConvert(common::Variant::DataType::Int64));
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
......
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