From 95bbaa1ec2c2fa39ecea4dc3c685f771551c59ff Mon Sep 17 00:00:00 2001 From: Kris Date: Sun, 28 Aug 2016 21:55:58 +0100 Subject: [PATCH] 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 --- gsl/gsl_byte | 6 ++++++ tests/byte_tests.cpp | 41 +++++++++++++++++++++++------------------ 2 files changed, 29 insertions(+), 18 deletions(-) diff --git a/gsl/gsl_byte b/gsl/gsl_byte index 91ce9d2..98749a7 100644 --- a/gsl/gsl_byte +++ b/gsl/gsl_byte @@ -106,6 +106,12 @@ constexpr IntegerType to_integer(byte b) noexcept return {b}; } +constexpr byte to_byte(unsigned char i) noexcept +{ + return static_cast(i); +} + + } // namespace gsl #ifdef _MSC_VER diff --git a/tests/byte_tests.cpp b/tests/byte_tests.cpp index f2f8026..d6d4823 100644 --- a/tests/byte_tests.cpp +++ b/tests/byte_tests.cpp @@ -43,6 +43,11 @@ SUITE(byte_tests) byte b = byte(12); CHECK(static_cast(b) == 12); } + + { + byte b = to_byte(12); + CHECK(static_cast(b) == 12); + } // waiting for C++17 enum class direct initializer support //{ @@ -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)); } }