1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <limits>
20 #include <type_traits>
21 
22 namespace bluetooth {
23 namespace common {
24 
25 // Check if input is within numeric limits of RawType
26 template <typename RawType, typename InputType>
IsNumberInNumericLimits(InputType input)27 bool IsNumberInNumericLimits(InputType input) {
28   // Only arithmetic types are supported
29   static_assert(std::is_arithmetic_v<RawType> && std::is_arithmetic_v<InputType>);
30   // Either both are signed or both are unsigned
31   static_assert(
32       (std::is_signed_v<RawType> && std::is_signed_v<InputType>) ||
33       (std::is_unsigned_v<RawType> && std::is_unsigned_v<InputType>));
34   if (std::numeric_limits<InputType>::max() > std::numeric_limits<RawType>::max()) {
35     if (input > std::numeric_limits<RawType>::max()) {
36       return false;
37     }
38   }
39   if (std::numeric_limits<InputType>::lowest() < std::numeric_limits<RawType>::lowest()) {
40     if (input < std::numeric_limits<RawType>::lowest()) {
41       return false;
42     }
43   }
44   return true;
45 }
46 
47 }  // namespace common
48 }  // namespace bluetooth