Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:54:49

0001 //----------------------------------*-C++-*----------------------------------//
0002 // Copyright 2022-2024 UT-Battelle, LLC, and other Celeritas developers.
0003 // See the top-level COPYRIGHT file for details.
0004 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0005 //---------------------------------------------------------------------------//
0006 //! \file corecel/math/QuantityIO.json.hh
0007 //---------------------------------------------------------------------------//
0008 #pragma once
0009 
0010 #include <string>
0011 #include <nlohmann/json.hpp>
0012 
0013 #include "corecel/Assert.hh"
0014 
0015 #include "Quantity.hh"
0016 
0017 namespace celeritas
0018 {
0019 //---------------------------------------------------------------------------//
0020 /*!
0021  * Read a quantity from a JSON file.
0022  */
0023 template<class UnitT, class ValueT>
0024 void from_json(nlohmann::json const& j, Quantity<UnitT, ValueT>& q)
0025 {
0026     static_assert(sizeof(UnitT::label()) > 0,
0027                   "Unit does not have a 'label' definition");
0028     if (j.is_array())
0029     {
0030         CELER_VALIDATE(j.size() == 2,
0031                        << "unexpected array size (" << j.size()
0032                        << ") for quantity in JSON input: should be [value, "
0033                           "\"units\"]");
0034         CELER_VALIDATE(j[1].get<std::string>() == UnitT::label(),
0035                        << "incorrect units '" << j[1].get<std::string>()
0036                        << "' in JSON input: expected '" << UnitT::label()
0037                        << "'");
0038         q = Quantity<UnitT, ValueT>{j[0].get<ValueT>()};
0039     }
0040     else
0041     {
0042         q = Quantity<UnitT, ValueT>{j.get<ValueT>()};
0043     }
0044 }
0045 
0046 //---------------------------------------------------------------------------//
0047 /*!
0048  * Write a quantity to a JSON file.
0049  */
0050 template<class UnitT, class ValueT>
0051 void to_json(nlohmann::json& j, Quantity<UnitT, ValueT> const& q)
0052 {
0053     static_assert(sizeof(UnitT::label()) > 0,
0054                   "Unit does not have a 'label' definition");
0055     j = {q.value(), UnitT::label()};
0056 }
0057 
0058 //---------------------------------------------------------------------------//
0059 }  // namespace celeritas