SST  15.1.0
StructuralSimulationToolkit
get_array_size.h
1 // Copyright 2009-2025 NTESS. Under the terms
2 // of Contract DE-NA0003525 with NTESS, the U.S.
3 // Government retains certain rights in this software.
4 //
5 // Copyright (c) 2009-2025, NTESS
6 // All rights reserved.
7 //
8 // This file is part of the SST software package. For license
9 // information, see the LICENSE file in the top level directory of the
10 // distribution.
11 
12 #ifndef SST_CORE_SERIALIZATION_IMPL_GET_ARRAY_SIZE_H
13 #define SST_CORE_SERIALIZATION_IMPL_GET_ARRAY_SIZE_H
14 
15 #ifndef SST_INCLUDING_SERIALIZER_H
16 #warning \
17  "The header file sst/core/serialization/impl/get_array_size.h should not be directly included as it is not part of the stable public API. The file is included in sst/core/serialization/serializer.h"
18 #endif
19 
20 #include <cstddef>
21 #include <cstdint>
22 #include <stdexcept>
23 #include <type_traits>
24 
25 namespace SST::Core::Serialization {
26 
27 // Convert array size to size_t, flagging errors
28 template <typename SIZE_T>
29 std::enable_if_t<std::is_integral_v<SIZE_T>, size_t>
30 get_array_size(SIZE_T size, const char* msg)
31 {
32  bool range_error;
33  if constexpr ( std::is_unsigned_v<SIZE_T> )
34  range_error = size > SIZE_MAX;
35  else if constexpr ( sizeof(SIZE_T) > sizeof(size_t) )
36  range_error = size < 0 || size > static_cast<SIZE_T>(SIZE_MAX);
37  else
38  range_error = size < 0;
39  if ( range_error ) throw std::range_error(msg);
40  return static_cast<size_t>(size);
41 }
42 
43 } // namespace SST::Core::Serialization
44 
45 #endif // SST_CORE_SERIALIZATION_IMPL_GET_ARRAY_SIZE_H