Added to_byte method for issue #329

I have added the to_byte method and updated the unit tests.

This gives slightly nicer syntax than static_cast, is better than the
c-style cast used in the unit test.

See: https://github.com/Microsoft/GSL/issues/329#issuecomment-240588515
This commit is contained in:
Kris 2016-08-28 21:55:58 +01:00
parent f8ef4e2355
commit 95bbaa1ec2
2 changed files with 29 additions and 18 deletions

View File

@ -106,6 +106,12 @@ constexpr IntegerType to_integer(byte b) noexcept
return {b};
}
constexpr byte to_byte(unsigned char i) noexcept
{
return static_cast<byte>(i);
}
} // namespace gsl
#ifdef _MSC_VER

View File

@ -44,6 +44,11 @@ SUITE(byte_tests)
CHECK(static_cast<unsigned char>(b) == 12);
}
{
byte b = to_byte(12);
CHECK(static_cast<unsigned char>(b) == 12);
}
// waiting for C++17 enum class direct initializer support
//{
// byte b { 14 };
@ -53,38 +58,38 @@ SUITE(byte_tests)
TEST(bitwise_operations)
{
byte b = byte(0xFF);
byte b = to_byte(0xFF);
byte a = byte(0x00);
CHECK((b | a) == byte(0xFF));
CHECK(a == byte(0x00));
byte a = to_byte(0x00);
CHECK((b | a) == to_byte(0xFF));
CHECK(a == to_byte(0x00));
a |= b;
CHECK(a == byte(0xFF));
CHECK(a == to_byte(0xFF));
a = byte(0x01);
CHECK((b & a) == byte(0x01));
a = to_byte(0x01);
CHECK((b & a) == to_byte(0x01));
a &= b;
CHECK(a == byte(0x01));
CHECK(a == to_byte(0x01));
CHECK((b ^ a) == byte(0xFE));
CHECK((b ^ a) == to_byte(0xFE));
CHECK(a == byte(0x01));
CHECK(a == to_byte(0x01));
a ^= b;
CHECK(a == byte(0xFE));
CHECK(a == to_byte(0xFE));
a = byte(0x01);
CHECK(~a == byte(0xFE));
a = to_byte(0x01);
CHECK(~a == to_byte(0xFE));
a = byte(0xFF);
CHECK((a << 4) == byte(0xF0));
CHECK((a >> 4) == byte(0x0F));
a = to_byte(0xFF);
CHECK((a << 4) == to_byte(0xF0));
CHECK((a >> 4) == to_byte(0x0F));
a <<= 4;
CHECK(a == byte(0xF0));
CHECK(a == to_byte(0xF0));
a >>= 4;
CHECK(a == byte(0x0F));
CHECK(a == to_byte(0x0F));
}
}