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

Add construction tests #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
62 changes: 62 additions & 0 deletions test/construction.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <cstddef>
#include <cstdint>
#include <cassert>
#include <iostream>
#include "saturating/types.hpp"

using std::cerr;

void test_no_overflow_on_unsigned_construction() {
uint_sat8_t s = 256;

constexpr auto expected = 255;

if (expected != s)
{
cerr << "failed. expected = " << expected << ", actual = " << +s << "\n";
assert(false);
}
}

void test_no_underflow_on_unsigned_construction() {
uint_sat8_t s = -1;

constexpr auto expected = 0;

if (expected != s)
{
cerr << "failed. expected = " << expected << ", actual = " << +s << "\n";
assert(false);
}
}

void test_no_overflow_on_signed_construction() {
int_sat8_t s = 129;

constexpr auto expected = 127;

if (expected != s)
{
cerr << "failed. expected = " << expected << ", actual = " << +s << "\n";
assert(false);
}
}

void test_no_underflow_on_signed_construction() {
int_sat8_t s = -129;

constexpr auto expected = -128;

if (expected != s)
{
cerr << "failed. expected = " << expected << ", actual = " << +s << "\n";
assert(false);
}
}

int main () {
test_no_overflow_on_unsigned_construction();
test_no_underflow_on_unsigned_construction();
test_no_overflow_on_signed_construction();
test_no_underflow_on_signed_construction();
}
11 changes: 9 additions & 2 deletions types.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,15 @@ namespace saturating {

/** Create a new zero-initialized saturated type. */
constexpr type() noexcept : value{0} {}

constexpr type(const value_type& val) noexcept : value{val} {}

template <typename U>
constexpr type(const U& val) noexcept
: value{
MAX < val ? MAX :
val < MIN ? MIN :
static_cast<value_type>(val)
}
{}

/**
* Create a new saturating type based on a given value.
Expand Down