Skip to content

Commit a395539

Browse files
author
Richard Musil
committed
Make std::filesystem::path conversion to/from UTF-8 encoded string explicit.
Signed-off-by: Richard Musil <[email protected]>
1 parent d0789e3 commit a395539

File tree

4 files changed

+1446
-1476
lines changed

4 files changed

+1446
-1476
lines changed

include/nlohmann/detail/conversions/from_json.hpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,12 @@ inline void from_json(const BasicJsonType& j, std_fs::path& p)
539539
{
540540
JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
541541
}
542-
p = *j.template get_ptr<const typename BasicJsonType::string_t*>();
542+
const auto& s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
543+
#ifdef JSON_HAS_CPP_20
544+
p = std_fs::path(std::u8string_view(reinterpret_cast<const char8_t*>(s.data()), s.size()));
545+
#else
546+
p = std_fs::u8path(s); // accepts UTF-8 encoded std::string in C++17, deprecated in C++20
547+
#endif
543548
}
544549
#endif
545550

include/nlohmann/detail/conversions/to_json.hpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,12 @@ inline void to_json(BasicJsonType& j, const T& t)
443443
template<typename BasicJsonType>
444444
inline void to_json(BasicJsonType& j, const std_fs::path& p)
445445
{
446-
j = p.string();
446+
#ifdef JSON_HAS_CPP_20
447+
const std::u8string s = p.u8string();
448+
j = std::string(s.begin(), s.end());
449+
#else
450+
j = p.u8string(); // returns std::string in C++17
451+
#endif
447452
}
448453
#endif
449454

single_include/nlohmann/json.hpp

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5319,7 +5319,12 @@ inline void from_json(const BasicJsonType& j, std_fs::path& p)
53195319
{
53205320
JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
53215321
}
5322-
p = *j.template get_ptr<const typename BasicJsonType::string_t*>();
5322+
const auto& s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
5323+
#ifdef JSON_HAS_CPP_20
5324+
p = std_fs::path(std::u8string_view(reinterpret_cast<const char8_t*>(s.data()), s.size()));
5325+
#else
5326+
p = std_fs::u8path(s); // accepts UTF-8 encoded std::string in C++17, deprecated in C++20
5327+
#endif
53235328
}
53245329
#endif
53255330

@@ -6080,7 +6085,12 @@ inline void to_json(BasicJsonType& j, const T& t)
60806085
template<typename BasicJsonType>
60816086
inline void to_json(BasicJsonType& j, const std_fs::path& p)
60826087
{
6083-
j = p.string();
6088+
#ifdef JSON_HAS_CPP_20
6089+
const std::u8string s = p.u8string();
6090+
j = std::string(s.begin(), s.end());
6091+
#else
6092+
j = p.u8string(); // returns std::string in C++17
6093+
#endif
60846094
}
60856095
#endif
60866096

0 commit comments

Comments
 (0)