Time Shield Library
C++ library for working with time
Loading...
Searching...
No Matches
mul_hi.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#pragma once
3#ifndef _TIME_SHIELD_DETAIL_MUL_HI_HPP_INCLUDED
4#define _TIME_SHIELD_DETAIL_MUL_HI_HPP_INCLUDED
5
8
9#include <cstdint>
10
11#if defined(_MSC_VER)
12# include <intrin.h>
13#endif
14
15namespace time_shield {
16namespace detail {
17
19 TIME_SHIELD_CONSTEXPR inline uint64_t mul_hi_u64_constexpr(uint64_t p_a, uint64_t p_b) noexcept {
20 const uint64_t a_low = p_a & 0xFFFFFFFFULL;
21 const uint64_t a_high = p_a >> 32;
22 const uint64_t b_low = p_b & 0xFFFFFFFFULL;
23 const uint64_t b_high = p_b >> 32;
24
25 const uint64_t p0 = a_low * b_low;
26 const uint64_t p1 = a_low * b_high;
27 const uint64_t p2 = a_high * b_low;
28 const uint64_t p3 = a_high * b_high;
29
30 const uint64_t carry = ((p0 >> 32) + (p1 & 0xFFFFFFFFULL) + (p2 & 0xFFFFFFFFULL)) >> 32;
31 return p3 + (p1 >> 32) + (p2 >> 32) + carry;
32 }
33
35 inline uint64_t mul_hi_u64(uint64_t p_a, uint64_t p_b) noexcept {
36#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
37 uint64_t high = 0;
38 (void)_umul128(p_a, p_b, &high);
39 return high;
40#else
41 const __uint128_t product = static_cast<__uint128_t>(p_a) * static_cast<__uint128_t>(p_b);
42 return static_cast<uint64_t>(product >> 64);
43#endif
44 }
45
47 inline uint64_t mul_shift_u64(uint64_t p_x, uint64_t p_c) noexcept {
48 return mul_hi_u64(p_x, p_c);
49 }
50
52 TIME_SHIELD_CONSTEXPR inline uint64_t mul_shift_u64_constexpr(uint64_t p_x, uint64_t p_c) noexcept {
53 return mul_hi_u64_constexpr(p_x, p_c);
54 }
55
56} // namespace detail
57} // namespace time_shield
58
59#endif // _TIME_SHIELD_DETAIL_MUL_HI_HPP_INCLUDED
uint64_t mul_shift_u64(uint64_t p_x, uint64_t p_c) noexcept
Alias for mul_hi_u64 used for shift-by-64 operations.
Definition mul_hi.hpp:47
TIME_SHIELD_CONSTEXPR uint64_t mul_hi_u64_constexpr(uint64_t p_a, uint64_t p_b) noexcept
Return the high 64 bits of a 64x64-bit multiplication (constexpr variant).
Definition mul_hi.hpp:19
uint64_t mul_hi_u64(uint64_t p_a, uint64_t p_b) noexcept
Return the high 64 bits of a 64x64-bit multiplication.
Definition mul_hi.hpp:35
TIME_SHIELD_CONSTEXPR uint64_t mul_shift_u64_constexpr(uint64_t p_x, uint64_t p_c) noexcept
Alias for mul_hi_u64_constexpr used for shift-by-64 operations.
Definition mul_hi.hpp:52
Main namespace for the Time Shield library.