Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve and expose bit_cast implementation #535

Merged
merged 2 commits into from
Sep 22, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
test: Add example bit_cast tests
chfast committed Sep 22, 2020
commit 88afddadcad277b2501ca1f8a1d09320fa5a98b9
1 change: 1 addition & 0 deletions test/unittests/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -10,6 +10,7 @@ target_link_libraries(fizzy-unittests PRIVATE fizzy::fizzy fizzy::test-utils GTe
target_sources(
fizzy-unittests PRIVATE
api_test.cpp
bit_cast_test.cpp
constexpr_vector_test.cpp
end_to_end_test.cpp
execute_call_test.cpp
46 changes: 46 additions & 0 deletions test/unittests/bit_cast_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Fizzy: A fast WebAssembly interpreter
// Copyright 2020 The Fizzy Authors.
// SPDX-License-Identifier: Apache-2.0

#include "cxx20/bit.hpp"
#include <gtest/gtest.h>
#include <array>

using namespace fizzy;
using namespace testing;


TEST(bit_cast, double_to_uint64)
{
// A test case from https://en.cppreference.com/w/cpp/numeric/bit_cast#Example.
EXPECT_EQ(bit_cast<uint64_t>(19880124.0), 0x4172f58bc0000000);
}

TEST(bit_cast, uint64_to_double)
{
// A test case from https://en.cppreference.com/w/cpp/numeric/bit_cast#Example.
EXPECT_EQ(bit_cast<double>(uint64_t{0x3fe9000000000000}), 0.781250);
}

TEST(bit_cast, uint32_to_int32)
{
EXPECT_EQ(bit_cast<int32_t>(uint32_t{0x80000000}), -2147483648);
EXPECT_EQ(bit_cast<int32_t>(uint32_t{0xffffffff}), -1);
}

TEST(bit_cast, int32_to_uint32)
{
EXPECT_EQ(bit_cast<uint32_t>(int32_t{-2}), 0xfffffffe);
EXPECT_EQ(bit_cast<uint32_t>(int32_t{1}), 1);
}

TEST(bit_cast, uint32_to_array)
{
// Uses "byte-symmetric" value to avoid handling endianness.
std::array<uint8_t, 4> bytes;
bytes = bit_cast<decltype(bytes)>(uint32_t{0xaabbbbaa});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could be non-symmetric to see the endianness

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's symmetric to avoid endianness issues.

EXPECT_EQ(bytes[0], 0xaa);
EXPECT_EQ(bytes[1], 0xbb);
EXPECT_EQ(bytes[2], 0xbb);
EXPECT_EQ(bytes[3], 0xaa);
}