Skip to content

saturate_cast #200

Description

@gpeterhoff

With C++26, there is std::saturate_cast https://en.cppreference.com/w/cpp/numeric/saturate_cast.html
Can you provide this as well?
I'm not sure if boost::core is the right library.
My implementation requires boost::is_integer (boostorg/type_traits#186), but they didn't understand what I meant and therefore rejected/closed it.

//	Distributed under the Boost Software License Version 1.0 https://www.boost.org/LICENSE_1_0.txt
//	Copyright Gero Peterhoff

#ifndef BOOST_CORE_SATURATE_CAST_HPP
#define BOOST_CORE_SATURATE_CAST_HPP

#include <boost/type_traits/is_integer.hpp>
#include <limits>



namespace boost
{
namespace core
{
template <typename To, typename From>
inline BOOST_CXX14_CONSTEXPR typename std::enable_if<boost::is_integer<To>::value && boost::is_integer<From>::value, To>::type	saturate_cast(const From& from)	noexcept
{
	using limits = std::numeric_limits<To>;

	BOOST_IF_CONSTEXPR (std::is_same<To, From>::value)
	{
		return from;
	}
	else BOOST_IF_CONSTEXPR (std::is_signed<To>::value && std::is_unsigned<From>::value)
	{
		using type = typename std::make_unsigned<To>::type;
		return
			(from > type(limits::max())) ? limits::max() :
			To(from);
	}
	else BOOST_IF_CONSTEXPR (std::is_unsigned<To>::value && std::is_signed<From>::value)
	{
		using type = typename std::make_unsigned<From>::type;
		return
			(from < 0) ? To{} :
			(type(from) > limits::max()) ? limits::max() :
			To(from);
	}
	else BOOST_IF_CONSTEXPR (std::is_signed<To>::value && std::is_signed<From>::value)
	{
		return
			(from < limits::min()) ? limits::min() :
			(from > limits::max()) ? limits::max() :
			To(from);
	}
	else
	{
		return
			(from > limits::max()) ? limits::max() :
			To(from);
	}
}

}	//	core
}	//	boost

#endif	//	BOOST_CORE_SATURATE_CAST_HPP

thx
Gero

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions