Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-04 10:45:27

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file corecel/OpaqueId.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <cstddef>
0010 #include <functional>
0011 #include <type_traits>
0012 
0013 #include "corecel/data/Ldg.hh"
0014 
0015 #include "Assert.hh"
0016 #include "Macros.hh"
0017 #include "Types.hh"
0018 
0019 #if !CELER_DEVICE_COMPILE
0020 #    include <ostream>
0021 #endif
0022 
0023 namespace celeritas
0024 {
0025 namespace detail
0026 {
0027 //---------------------------------------------------------------------------//
0028 //! Sentinel value for an unassigned opaque ID
0029 template<class I>
0030 inline constexpr I nullid_value{static_cast<I>(-1)};
0031 
0032 #if !CELER_DEVICE_COMPILE
0033 template<class I>
0034 void stream_opaqueid_impl(std::ostream&, I, I);
0035 #endif
0036 
0037 //---------------------------------------------------------------------------//
0038 }  // namespace detail
0039 
0040 //! Tag type used for \c nullid
0041 struct nullid_t
0042 {
0043     constexpr explicit nullid_t(int) {}
0044 };
0045 
0046 //! Tag instance used to instantiate and compare to a null OpaqueId
0047 inline constexpr nullid_t nullid{0};
0048 
0049 //---------------------------------------------------------------------------//
0050 /*!
0051  * Type-safe "optional" index for accessing an array or collection of data.
0052  *
0053  * \tparam TagT Type of an item at the index corresponding to this ID
0054  * \tparam IndexT Unsigned integer acting as the stored value
0055  *
0056  * Indexing into arrays with integers, rather than storing pointers, is
0057  * \em key to easy and safe data management across host/device boundaries.
0058  * Pointers in C++ can act as a reference to an array or element of data, and
0059  * they also have a \em type, which not only gives the stride width in bytes
0060  * but also <em>prevents accidental aliasing</em>.
0061  *
0062  * The \c OpaqueId class is an attempt to model integer indexing
0063  * (device-friendly) with pointer semantics (type-safe).
0064  * Annotating index offsets with a type gives the offsets a semantic meaning,
0065  * and it gives the developer compile-time type safety.
0066  * As an example, it prevents index arguments in a function call from being
0067  * provided out of order.
0068  *
0069  * The typical usage of an OpaqueId should be as \c std::optional<IndexT>.
0070  * The default-constructed value, \c nullid, cannot be used to index into an
0071  * array, nor does it represent a valid element.
0072  * An \c OpaqueId object evaluates to \c true if it has a value
0073  * (`OpaqueId{3}`), or \c false if it does not (`OpaqueId{}`).
0074  * The invalid state is usually referred to in the codebase as a "null ID".
0075  * Analogous to \c std::optional, \c nullid can be used for comparison,
0076  * assignment, and construction.
0077  *
0078  * \par Construction
0079  * - Default: result is \c nullid
0080  * - Implicitly from \c nullid
0081  * - Explicitly from a compatible unsigned integer
0082  * - Via \c id_cast for safe construction from general (or differently sized)
0083  *   integers
0084  *
0085  * \par Usage
0086  * - Check for nullity with \c bool or by comparing with \c nullid
0087  * - Check for validity as a container index with
0088  *   <code>id &lt; vec.size()</code>
0089  * - Access value with \c operator* : <code>vec[*id]</code>
0090  * - Access data with \c Collection::operator[]
0091  * - Loop over consecutive IDs with \c range
0092  * - Pre- and post- increment and decrement
0093  * - Subtract two IDs to get a difference
0094  *
0095  * The OpaqueId is hashable, sortable, and printable.
0096  * It can be loaded via cached device memory using \c ldg .
0097  *
0098  * \note A valid ID will always compare less than a null ID: you can use
0099  *      \c std::partition and \c erase to remove null IDs from a vector.
0100  *
0101  * \note Comparators are defined as inline friend functions to allow
0102  * ADL-assisted conversion, including from \c LdgWrapper.
0103  *
0104  * \par Related helper functions and types
0105  * - \c nullid is an instance of \c nullid_t that compares to any OpaqueId as
0106  *   its "null" value.
0107  * - \c is_opaque_id_v allows checking for generic types
0108  * - \c MakeSize_t is a descriptive type alias to get the unsigned integer
0109  *   \c value_type of an opaque ID, used for container capacities.
0110  * - \c id_cast safely converts integers to OpaqueId.
0111  *
0112  * \par About the TagT template parameter
0113  * If this class is used for indexing into an array, then \c TagT argument
0114  * should usually be the value type of the array:
0115  * \code
0116  * FooRecord operator[](OpaqueId<FooRecord>);
0117  * \endcode
0118  * Otherwise, the convention is to use an anonymous tag:
0119  * \code
0120   using FooId = OpaqueId<struct Foo_>;
0121  * \endcode
0122  */
0123 template<class TagT, class IndexT = ::celeritas::size_type>
0124 class OpaqueId
0125 {
0126     static_assert(std::is_unsigned_v<IndexT> && !std::is_same_v<IndexT, bool>,
0127                   "IndexT must be unsigned.");
0128 
0129     static constexpr bool ndebug = !CELERITAS_DEBUG;
0130 
0131   public:
0132     //!@{
0133     //! \name Type aliases
0134     using tag_type = TagT;
0135     using value_type = IndexT;  // like std::optional
0136     using index_type = IndexT;
0137     using difference_type = std::make_signed_t<IndexT>;
0138     using size_type = value_type;  // DEPRECATED
0139     //!@}
0140 
0141   public:
0142     //! Construct implicitly from a null type
0143     CELER_CEF OpaqueId(nullid_t) : value_(null_) {}
0144 
0145     //! Default to null state
0146     CELER_CEF OpaqueId() : OpaqueId(nullid) {}
0147 
0148     //! Construct explicitly with a stored value (validity *not* checked)
0149     explicit CELER_CEF OpaqueId(value_type index) : value_(index) {}
0150 
0151     //! Whether this ID is in a valid (assigned) state
0152     explicit CELER_CEF operator bool() const noexcept
0153     {
0154         return value_ != null_;
0155     }
0156 
0157     //! Unchecked dereference: caller must ensure the ID is valid
0158     CELER_CEF value_type operator*() const noexcept { return value_; }
0159 
0160     //! Get the value, asserting non-null in debug builds
0161     CELER_CEF value_type value() const noexcept(ndebug)
0162     {
0163         CELER_EXPECT(*this);
0164         return value_;
0165     }
0166 
0167     //! Access the underlying data for cached loading on device
0168     CELER_CEF value_type const* data() const noexcept { return &value_; }
0169 
0170     //!@{
0171     //! \name Pointer-like operators
0172     //! \note Incrementing/decrementing to/from null is prohibited
0173 
0174     CELER_CEF OpaqueId& operator++() noexcept(ndebug)
0175     {
0176         CELER_EXPECT(value_ < (null_ - 1));
0177         value_ += 1;
0178         return *this;
0179     }
0180 
0181     CELER_CEF OpaqueId operator++(int) noexcept(ndebug)
0182     {
0183         OpaqueId old{*this};
0184         ++*this;
0185         return old;
0186     }
0187 
0188     CELER_CEF OpaqueId& operator--() noexcept(ndebug)
0189     {
0190         CELER_EXPECT(*this && value_ > 0);
0191         value_ -= 1;
0192         return *this;
0193     }
0194 
0195     CELER_CEF OpaqueId operator--(int) noexcept(ndebug)
0196     {
0197         OpaqueId old{*this};
0198         --*this;
0199         return old;
0200     }
0201 
0202     //!@}
0203 
0204     //!@{
0205     //! \name Pointer-like arithmetic
0206     //! Get the distance between two opaque IDs
0207     CELER_FUNCTION friend difference_type operator-(OpaqueId self,
0208                                                     OpaqueId other)
0209     {
0210         CELER_EXPECT(self);
0211         CELER_EXPECT(other);
0212         return static_cast<difference_type>(*self - *other);
0213     }
0214 
0215     //! Increment an opaque ID by an offset, checking against underflow
0216     template<class J>
0217     CELER_FUNCTION friend auto operator+(OpaqueId id, J offset)
0218         -> std::enable_if_t<std::is_integral_v<J>, OpaqueId>
0219     {
0220         CELER_EXPECT(id);
0221         CELER_EXPECT(OpaqueId::is_safe_offset(*id, offset));
0222 
0223         // Note: an extra cast is needed for short IndexT with long J
0224         return OpaqueId{static_cast<IndexT>(*id + offset)};
0225     }
0226 
0227     //! Increment an opaque ID by an offset (symmetric)
0228     template<class J>
0229     CELER_FUNCTION friend auto operator+(J offset, OpaqueId id)
0230         -> std::enable_if_t<std::is_integral_v<J>, OpaqueId>
0231     {
0232         return id + offset;
0233     }
0234 
0235     //! Decrement an opaque ID by an offset
0236     template<class J>
0237     CELER_FUNCTION friend auto operator-(OpaqueId id, J offset)
0238         -> std::enable_if_t<std::is_integral_v<J>, OpaqueId>
0239     {
0240         CELER_EXPECT(id);
0241         CELER_EXPECT(offset <= 0 || static_cast<IndexT>(offset) <= *id);
0242         // Note: an extra cast is needed for short I with long J
0243         return OpaqueId{static_cast<IndexT>(*id - static_cast<IndexT>(offset))};
0244     }
0245     //!@}
0246 
0247     //!@{
0248     //! \name Deprecated access
0249     //! \deprecated Remove in v1.0
0250 
0251     //! Get the ID's value: use \c value() instead
0252     CELER_CEF value_type get() const noexcept(ndebug) { return this->value(); }
0253 
0254     //! Get the value without checking: use \c operator* instead
0255     CELER_CEF value_type unchecked_get() const noexcept { return value_; }
0256 
0257     //!@}
0258 
0259     //// TEMPLATE FRIEND OPERATORS ////
0260 
0261 #define CELER_DEFINE_OPAQUEID_CMP(TOKEN) \
0262     CELER_CEF friend bool operator TOKEN(OpaqueId lhs, OpaqueId rhs) noexcept \
0263     { \
0264         return *lhs TOKEN * rhs; \
0265     }
0266 
0267     //!@{
0268     //! \name Compare two OpaqueId of the same type
0269     CELER_DEFINE_OPAQUEID_CMP(==)
0270     CELER_DEFINE_OPAQUEID_CMP(!=)
0271     CELER_DEFINE_OPAQUEID_CMP(<)
0272     CELER_DEFINE_OPAQUEID_CMP(>)
0273     CELER_DEFINE_OPAQUEID_CMP(<=)
0274     CELER_DEFINE_OPAQUEID_CMP(>=)
0275     //!@}
0276 
0277     //!@{
0278     //! \name Compare with nullid
0279     CELER_CEF friend bool operator==(OpaqueId id, nullid_t) noexcept
0280     {
0281         return !id;
0282     }
0283     CELER_CEF friend bool operator==(nullid_t, OpaqueId id) noexcept
0284     {
0285         return !id;
0286     }
0287     CELER_CEF friend bool operator!=(OpaqueId id, nullid_t) noexcept
0288     {
0289         return static_cast<bool>(id);
0290     }
0291     CELER_CEF friend bool operator!=(nullid_t, OpaqueId id) noexcept
0292     {
0293         return static_cast<bool>(id);
0294     }
0295     //!@}
0296 
0297     //! Allow loading via \c ldg
0298     CELER_CONSTEXPR_FUNCTION friend OpaqueId ldg(OpaqueId const* id)
0299     {
0300         using ::celeritas::ldg;
0301         return OpaqueId{ldg(&id->value_)};
0302     }
0303 
0304 #undef CELER_DEFINE_OPAQUEID_CMP
0305 #define CELER_DEFINE_OPAQUEID_CMP(TOKEN) \
0306     template<class J> \
0307     CELER_CEF friend auto operator TOKEN(OpaqueId lhs, J rhs) noexcept \
0308         -> std::enable_if_t<std::is_unsigned_v<J>, bool> \
0309     { \
0310         return lhs && (static_cast<J>(*lhs) TOKEN rhs); \
0311     }
0312 
0313     //!@{
0314     //! \name Compare with unsigned int
0315     //! This allows size checking for containers
0316     CELER_DEFINE_OPAQUEID_CMP(<)
0317     CELER_DEFINE_OPAQUEID_CMP(<=)
0318     //!@}
0319 
0320 #undef CELER_DEFINE_OPAQUEID_CMP
0321 
0322 #if !CELER_DEVICE_COMPILE
0323     //! Output an opaque ID's value or a placeholder if unavailable.
0324     CELER_FORCEINLINE friend std::ostream& operator<<(std::ostream& os,
0325                                                       OpaqueId v)
0326     {
0327         detail::stream_opaqueid_impl(os, v.value_, v.null_);
0328         return os;
0329     }
0330 #endif
0331 
0332   private:
0333     //// DATA ////
0334 
0335     value_type value_;
0336 
0337     //! Value indicating the ID is not assigned
0338     static constexpr value_type null_ = detail::nullid_value<value_type>;
0339 
0340     //// HELPER FUNCTIONS ////
0341 
0342     template<class J>
0343     static CELER_CEF bool is_safe_offset(IndexT value, J offset)
0344     {
0345         if constexpr (std::is_unsigned_v<J>)
0346         {
0347             return true;
0348         }
0349         else
0350         {
0351             if (offset >= 0)
0352             {
0353                 // NOTE: we do not check for overflow
0354                 return true;
0355             }
0356             return static_cast<IndexT>(J{0} - offset) <= value;
0357         }
0358     }
0359 };
0360 
0361 //! Specialize size type for opaque IDs
0362 template<class I, class V>
0363 struct MakeSize<OpaqueId<I, V>>
0364 {
0365     using type = V;
0366 };
0367 
0368 //! Automatically load read-only OpaqueIDs with LDG
0369 template<class I, class V>
0370 struct IsAutoLdg<OpaqueId<I, V>> : std::true_type
0371 {
0372 };
0373 
0374 //---------------------------------------------------------------------------//
0375 // DETAIL IMPLEMENTATION
0376 // (not a separate file due to living in the top level)
0377 //---------------------------------------------------------------------------//
0378 
0379 namespace detail
0380 {
0381 //---------------------------------------------------------------------------//
0382 //! Safely cast from one integer T to another J, avoiding the sentinel value
0383 template<class T, class J>
0384 inline CELER_FUNCTION T id_cast_impl(J value) noexcept(!CELERITAS_DEBUG)
0385 {
0386     constexpr auto null_val = detail::nullid_value<T>;
0387 
0388     if constexpr (std::is_signed_v<J>)
0389     {
0390         CELER_EXPECT(value >= 0);
0391     }
0392 
0393     if constexpr (!std::is_same_v<T, J>)
0394     {
0395         // Check that the cast value is within the integer range [0, N-1)
0396         using C = std::common_type_t<T, std::make_unsigned_t<J>>;
0397         if constexpr (std::is_signed_v<C>)
0398         {
0399             CELER_EXPECT(static_cast<C>(value) >= 0);
0400         }
0401         CELER_EXPECT(static_cast<C>(value) < static_cast<C>(null_val));
0402     }
0403     else
0404     {
0405         // Check that value is *not* the null value
0406         CELER_EXPECT(static_cast<T>(value) != null_val);
0407     }
0408 
0409     return static_cast<T>(value);
0410 }
0411 
0412 //---------------------------------------------------------------------------//
0413 //! Template matching to determine if T is an OpaqueId
0414 template<class T>
0415 struct IsOpaqueId : std::false_type
0416 {
0417 };
0418 
0419 template<class I, class V>
0420 struct IsOpaqueId<OpaqueId<I, V>> : std::true_type
0421 {
0422 };
0423 
0424 #if !CELER_DEVICE_COMPILE
0425 // Print an opaque ID: ignore instantiator to reduce duplicate symbols
0426 template<class V>
0427 inline void stream_opaqueid_impl(std::ostream& os, V v, V nullint)
0428 {
0429     os << '{';
0430     if (v != nullint)
0431     {
0432         os << v;
0433     }
0434     os << '}';
0435 }
0436 
0437 // Specialization avoids printing integers as '\x1'
0438 template<>
0439 CELER_FORCEINLINE void stream_opaqueid_impl(
0440     std::ostream& os, unsigned char v, unsigned char nullid)
0441 {
0442     return stream_opaqueid_impl(
0443         os, static_cast<unsigned int>(v), static_cast<unsigned int>(nullid));
0444 }
0445 #endif
0446 
0447 //---------------------------------------------------------------------------//
0448 }  // namespace detail
0449 
0450 //---------------------------------------------------------------------------//
0451 // FREE IMPLEMENTATIONS
0452 //---------------------------------------------------------------------------//
0453 
0454 //! True if T is an OpaqueID
0455 template<class T>
0456 inline constexpr bool is_opaque_id_v
0457     = detail::IsOpaqueId<std::remove_cv_t<T>>::value;
0458 
0459 //---------------------------------------------------------------------------//
0460 /*!
0461  * Safely create an OpaqueId from an integer of any type.
0462  *
0463  * This asserts that the integer is in the \em valid range of the target ID
0464  * type, and casts to it.
0465  *
0466  * \note The value cannot be the underlying "null" value; i.e.
0467  * <code> static_cast<FooId>(*FooId{}) </code> will not work.
0468  */
0469 template<class IdT, class J>
0470 inline CELER_FUNCTION auto id_cast(J value) noexcept(!CELERITAS_DEBUG)
0471     -> std::enable_if_t<is_opaque_id_v<IdT> && std::is_integral_v<J>, IdT>
0472 {
0473     return IdT{detail::id_cast_impl<typename IdT::value_type, J>(value)};
0474 }
0475 
0476 //---------------------------------------------------------------------------//
0477 }  // namespace celeritas
0478 
0479 //! \cond
0480 namespace std
0481 {
0482 //! Specialization for std::hash for unordered storage.
0483 template<class I, class T>
0484 struct hash<celeritas::OpaqueId<I, T>>
0485 {
0486     std::size_t operator()(celeritas::OpaqueId<I, T> const& id) const noexcept
0487     {
0488         return std::hash<T>()(*id);
0489     }
0490 };
0491 }  // namespace std
0492 //! \endcond