Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-17 08:54:08

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/math/QuantityIO.json.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <string>
0010 #include <nlohmann/json.hpp>
0011 
0012 #include "corecel/Assert.hh"
0013 
0014 #include "Quantity.hh"
0015 
0016 namespace celeritas
0017 {
0018 //---------------------------------------------------------------------------//
0019 /*!
0020  * Read a quantity from a JSON file.
0021  */
0022 template<class UnitT, class ValueT>
0023 void from_json(nlohmann::json const& j, Quantity<UnitT, ValueT>& q)
0024 {
0025     static_assert(sizeof(UnitT::label()) > 0,
0026                   "Unit does not have a 'label' definition");
0027     if (j.is_array())
0028     {
0029         CELER_VALIDATE(j.size() == 2,
0030                        << "unexpected array size (" << j.size()
0031                        << ") for quantity in JSON input: should be [value, "
0032                           "\"units\"]");
0033         CELER_VALIDATE(j[1].get<std::string>() == UnitT::label(),
0034                        << "incorrect units '" << j[1].get<std::string>()
0035                        << "' in JSON input: expected '" << UnitT::label()
0036                        << "'");
0037         q = Quantity<UnitT, ValueT>{j[0].get<ValueT>()};
0038     }
0039     else
0040     {
0041         q = Quantity<UnitT, ValueT>{j.get<ValueT>()};
0042     }
0043 }
0044 
0045 //---------------------------------------------------------------------------//
0046 /*!
0047  * Write a quantity to a JSON file.
0048  */
0049 template<class UnitT, class ValueT>
0050 void to_json(nlohmann::json& j, Quantity<UnitT, ValueT> const& q)
0051 {
0052     static_assert(sizeof(UnitT::label()) > 0,
0053                   "Unit does not have a 'label' definition");
0054     j = {q.value(), UnitT::label()};
0055 }
0056 
0057 //---------------------------------------------------------------------------//
0058 }  // namespace celeritas