| 1 | // |
| 2 | // SPDX-FileCopyrightText: Copyright 2026 Arm Limited and/or its affiliates <open-source-office@arm.com> |
| 3 | // |
| 4 | // SPDX-License-Identifier: Apache-2.0 |
| 5 | // |
| 6 | |
| 7 | #pragma once |
| 8 | |
| 9 | #include <limits> |
| 10 | #include <optional> |
| 11 | #include <type_traits> |
| 12 | |
| 13 | namespace kai::test { |
| 14 | |
| 15 | /// Multiply two non-negative integers and detect overflow. |
| 16 | template <typename T> |
| 17 | [[nodiscard]] inline std::optional<T> safe_mul(T a, T b) noexcept { |
| 18 | static_assert(std::is_integral_v<T>); |
| 19 | if (a == 0 || b == 0) { |
| 20 | return static_cast<T>(0); |
| 21 | } |
| 22 | if (a > std::numeric_limits<T>::max() / b) { |
| 23 | return std::nullopt; |
| 24 | } |
| 25 | return static_cast<T>(a * b); |
| 26 | } |
| 27 | |
| 28 | } // namespace kai::test |