3#include <system/value_tuple.h>
4#include "system/text/json/json_collection_extensions.h"
5#include <system/type_info.h>
6#include <system/type_code.h>
7#include <system/text/regularexpressions/regex.h>
8#include <system/string_comparison.h>
9#include <system/string_comparer.h>
10#include <system/span.h>
11#include <system/scope_guard.h>
12#include <system/primitive_types.h>
13#include <system/object_ext.h>
14#include <system/memory_extensions.h>
15#include <system/diagnostics/debug.h>
16#include <system/details/stack_array.h>
17#include <system/details/pointer_collection_helpers.h>
18#include <system/details/patterns.h>
19#include <system/details/object_builder.h>
20#include <system/details/dispose_guard.h>
21#include <system/default.h>
22#include <system/constraints.h>
23#include <system/collections/list.h>
24#include <system/collections/ienumerator.h>
25#include <system/collections/dictionary.h>
26#include <system/collections/concurrent/concurrent_dictionary.h>
27#include <system/char.h>
28#include <system/boxed_value.h>
29#include <system/array.h>
33#include "system/text/json/serialization/converters/value/json_primitive_converter.h"
34#include "system/text/json/serialization/converters/value/enum_converter_options.h"
35#include "system/text/json/json_naming_policy.h"
36#include "system/text/json/serialization/json_serializer_options.h"
37#include "system/text/json/json_encoded_text.h"
38#include "system/text/json/reader/utf8_json_reader.h"
39#include "system/text/json/json_token_type.h"
40#include "system/text/json/throw_helper.h"
41#include "system/text/json/writer/utf8_json_writer.h"
42#include "system/text/json/nodes/json_array.h"
43#include "system/text/json/nodes/json_node.h"
44#include "system/text/json/serialization/json_value_type.h"
45#include "system/text/json/json_constants.h"
46#include "system/text/json/json_helpers.h"
47#include "system/text/value_string_builder.h"
79 typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
80 RTTI_INFO_TEMPLATE_CLASS(
ThisType, ThisTypeBaseTypesInfo);
86 enum class EnumFieldNameKind
97 typedef EnumFieldInfo ThisType;
100 typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
101 RTTI_INFO_TEMPLATE_CLASS(ThisType, ThisTypeBaseTypesInfo);
107 EnumFieldNameKind get_Kind()
119 return pr_OriginalName;
133 if (current->get_Kind() == EnumFieldNameKind::Default)
140 if (other->get_Kind() == EnumFieldNameKind::Default)
159 auto conflictingField_enumerator = (conflictingFields)->GetEnumerator();
160 while (conflictingField_enumerator->MoveNext())
162 auto&& conflictingField = conflictingField_enumerator->get_Current();
164 if (ConflictsWith(conflictingField, other))
171 conflictingFields->Add(other);
187 auto matchingField_enumerator = (_conflictingFields)->GetEnumerator();
188 while (matchingField_enumerator->MoveNext())
190 auto&& matchingField = matchingField_enumerator->get_Current();
194 return matchingField;
203 EnumFieldInfo(uint64_t key, EnumFieldNameKind kind, String originalName, String jsonName)
204 : pr_Kind(kind), pr_Key(key), pr_OriginalName(originalName), pr_JsonName(jsonName)
210 virtual ~EnumFieldInfo()
214 #ifdef ASPOSE_GET_SHARED_MEMBERS
215 void GetSharedMembers(System::Object::shared_members_type& result)
const override
217 Object::GetSharedMembers(result);
219 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::EnumFieldInfo::_conflictingFields", this->_conflictingFields);
220 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::EnumFieldInfo::pr_Kind", this->pr_Kind);
227 EnumFieldNameKind pr_Kind;
229 String pr_OriginalName;
239 System::Details::ThisProtector __local_self_ref(
this);
241 s_enumTypeCode = GetEnumTypeCode();
242 s_isSignedEnum = std::is_signed<typename std::underlying_type<T>::type>::value;
243 s_isFlagsEnum =
false;
245 _converterOptions = converterOptions;
246 _namingPolicy = namingPolicy;
247 _enumFieldInfo = ResolveEnumFields(namingPolicy);
250 _nameCacheForWriting = System::MakeObject<Collections::Concurrent::ConcurrentDictionary<uint64_t, JsonEncodedText>>();
251 _nameCacheForReading = System::MakeObject<Collections::Concurrent::ConcurrentDictionary<String, uint64_t>>();
261 existingFieldInfo->AppendConflictingField(fieldInfo);
266 AddToEnumFieldIndex(fieldInfo);
269 _nameCacheForWriting->TryAdd(fieldInfo->get_Key(), encodedName);
270 _nameCacheForReading->TryAdd(fieldInfo->get_JsonName(), fieldInfo->get_Key());
273 if (!(namingPolicy ==
nullptr))
279 if (fieldInfo->get_Kind() == EnumFieldNameKind::NamingPolicy)
289 ASPOSE_UNUSED(typeToConvert);
290 ASPOSE_UNUSED(options);
295 if (TryParseEnumFromString(
System::Ref(reader), result))
304 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetInt32()));
308 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetUInt32()));
312 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetInt64()));
316 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetUInt64()));
320 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetByte()));
324 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetSByte()));
328 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetInt16()));
332 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.
GetUInt16()));
337 return System::Default<T>();
345 uint64_t key = ConvertToUInt64(
value);
348 if (_nameCacheForWriting->TryGetValue(key, formatted))
350 writer->WriteStringValue(formatted);
354 if (IsDefinedValueOrCombinationOfValues(key))
357 String stringValue = FormatEnumAsString(key,
value,
nullptr);
358 if (_nameCacheForWriting->get_Count() < NameCacheSizeSoftLimit)
361 writer->WriteStringValue(formatted);
362 _nameCacheForWriting->TryAdd(key, formatted);
368 writer->WriteStringValue(stringValue);
382 writer->WriteNumberValue(ConvertToInt64(
value));
386 writer->WriteNumberValue(ConvertToUInt64(
value));
392 ASPOSE_UNUSED(typeToConvert);
393 ASPOSE_UNUSED(options);
398 if (!TryParseEnumFromString(
System::Ref(reader), result))
408 ASPOSE_UNUSED(isWritingExtensionDataProperty);
410 if (dictionaryKeyPolicy == _namingPolicy)
412 dictionaryKeyPolicy =
nullptr;
414 uint64_t key = ConvertToUInt64(
value);
417 if (dictionaryKeyPolicy ==
nullptr && _nameCacheForWriting->TryGetValue(key, formatted))
419 writer->WritePropertyName(formatted);
423 if (IsDefinedValueOrCombinationOfValues(key))
426 String stringValue = FormatEnumAsString(key,
value, dictionaryKeyPolicy);
427 if (dictionaryKeyPolicy ==
nullptr && _nameCacheForWriting->get_Count() < NameCacheSizeSoftLimit)
431 writer->WritePropertyName(formatted);
432 _nameCacheForWriting->TryAdd(key, formatted);
438 writer->WritePropertyName(stringValue);
446 writer->WritePropertyName(ConvertToInt64(
value));
450 writer->WritePropertyName(key);
461 if (allowsString && allowsNumber)
485 #ifdef ASPOSE_GET_SHARED_MEMBERS
486 void GetSharedMembers(System::Object::shared_members_type& result)
const override
490 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::_converterOptions", this->_converterOptions);
491 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::_namingPolicy", this->_namingPolicy);
492 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::_enumFieldInfo", this->_enumFieldInfo);
493 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::_enumFieldInfoIndex", this->_enumFieldInfoIndex);
494 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::_nameCacheForWriting", this->_nameCacheForWriting);
495 result.Add(
"System::Text::Json::Serialization::Converters::EnumConverter::_nameCacheForReading", this->_nameCacheForReading);
502 static bool s_isSignedEnum;
503 static bool s_isFlagsEnum;
510 static const int32_t NameCacheSizeSoftLimit = 64;
519 System::Details::StackArray<char16_t, System::Text::Json::JsonConstants::StackallocCharThreshold> array_0;
522 int32_t charsWritten = reader.
CopyString(charBuffer);
523 charBuffer = charBuffer.Slice(0, charsWritten);
527 if (lookup->TryGetValue(source, key))
529 result = ConvertFromUInt64(key);
543 result = System::Default<T>();
549 success = TryParseNamedEnum(source, result);
552 if (success && _nameCacheForReading->get_Count() < NameCacheSizeSoftLimit)
554 lookup->TryAdd(source, ConvertToUInt64(result));
558 if (!(rentedBuffer ==
nullptr))
567 bool TryParseNamedEnum(String source, T& result)
575 ReadOnlySpan<char16_t> next;
580 rest = System::Default<System::ReadOnlySpan<char16_t>>();
589 if (lookup->TryGetValue(
System::ObjectExt::ToString(next), firstResult) && System::Is<EnumFieldInfo>(firstResult->GetMatchingField(next), match))
591 key |= match->get_Key();
595 result = System::Default<T>();
597 }
while (!rest.get_IsEmpty());
599 result = ConvertFromUInt64(key);
605 typedef typename std::underlying_type<T>::type Underlying;
606 if (
sizeof(Underlying) == 1)
610 if (
sizeof(Underlying) == 2)
614 if (
sizeof(Underlying) == 4)
621 static uint64_t ConvertToUInt64(T value)
623 return s_enumTypeCode ==
System::TypeCode::Int32 ? (uint64_t)System::ExplicitCast<int32_t>(System::ExplicitCast<System::Object>(value)) :
624 s_enumTypeCode ==
System::TypeCode::UInt32 ? System::ExplicitCast<uint32_t>(System::ExplicitCast<System::Object>(value)) :
625 s_enumTypeCode ==
System::TypeCode::Int64 ? (uint64_t)System::ExplicitCast<int64_t>(System::ExplicitCast<System::Object>(value)) :
633 static int64_t ConvertToInt64(T value)
636 return s_enumTypeCode ==
System::TypeCode::Int32 ? System::ExplicitCast<int32_t>(System::ExplicitCast<System::Object>(value)) :
642 static T ConvertFromUInt64(uint64_t value)
644 return s_enumTypeCode ==
System::TypeCode::Int32 ? System::ExplicitCast<T>(System::ExplicitCast<System::Object>((int32_t)value)) :
656 #if defined(__MSVC__)
657 #pragma warning( push )
658 #pragma warning(disable : 4715)
659 #pragma warning(disable : 4700)
660 #pragma warning(disable : 4701)
661 #elif defined(__GNUC__)
662 #pragma GCC diagnostic push
663 #pragma GCC diagnostic ignored "-Wreturn-type"
668 CODEPORTING_DEBUG_ASSERT2(s_isFlagsEnum || (!(dictionaryKeyPolicy ==
nullptr) &&
System::Enum<T>::IsDefined(value)), u
"must either be a flag type or computing a dictionary key policy.");
672 System::Details::StackArray<char16_t, System::Text::Json::JsonConstants::StackallocCharThreshold> array_0;
673 ValueStringBuilder sb = ValueStringBuilder(array_0);
675 uint64_t remainingBits = key;
678 uint64_t fieldKey = enumField->get_Key();
679 if (fieldKey == 0 ? key == 0 : (remainingBits & fieldKey) == fieldKey)
681 remainingBits &= ~fieldKey;
682 String name = !(dictionaryKeyPolicy ==
nullptr) ? ResolveAndValidateJsonName(enumField->get_OriginalName(), dictionaryKeyPolicy, enumField->get_Kind()) : enumField->get_JsonName();
684 if (sb.get_Length() > 0)
691 if (remainingBits == 0)
706 if (enumField->get_Key() == key)
708 return ResolveAndValidateJsonName(enumField->get_OriginalName(), dictionaryKeyPolicy, enumField->get_Kind());
712 CODEPORTING_DEBUG_FAIL1(u
"should not have been reached.");
716 #if defined(__MSVC__)
717 #pragma warning( pop )
718 #elif defined(__GNUC__)
719 #pragma GCC diagnostic pop
722 bool IsDefinedValueOrCombinationOfValues(uint64_t key)
726 uint64_t remainingBits = key;
730 uint64_t fieldKey = fieldInfo->get_Key();
731 if (fieldKey == 0 ? key == 0 : (remainingBits & fieldKey) == fieldKey)
733 remainingBits &= ~fieldKey;
735 if (remainingBits == 0)
748 if (fieldInfo->get_Key() == key)
768 auto enumFields = System::MakeArray<System::SharedPtr<System::Text::Json::Serialization::Converters::EnumConverter<T>::EnumFieldInfo>>(names->get_Length());
769 for (int32_t i = 0; i < names->get_Length(); i++)
771 String originalName = names[i];
773 uint64_t key = ConvertToUInt64(value);
774 EnumFieldNameKind kind;
776 String attributeName;
777 if (!(enumMemberAttributes ==
nullptr) && enumMemberAttributes->TryGetValue(originalName, attributeName))
779 originalName = attributeName;
787 String jsonName = ResolveAndValidateJsonName(originalName, namingPolicy, kind);
788 enumFields[i] = System::MakeObject<EnumFieldInfo>(key, kind, originalName, jsonName);
795 enumFields = TopologicalSortEnumFields(enumFields);
807 name = namingPolicy->ConvertName(name);
823 if (enumFields->get_Length() <= 1)
828 auto indices = System::MakeArray<System::ValueTuple<int32_t, int32_t>>(enumFields->get_Length());
829 for (int32_t i = 0; i < enumFields->get_Length(); i++)
838 auto sortedFields = System::MakeArray<System::SharedPtr<System::Text::Json::Serialization::Converters::EnumConverter<T>::EnumFieldInfo>>(enumFields->get_Length());
839 for (int32_t i = 0; i < indices->get_Length(); i++)
842 int32_t
index = indices[i].template
Item<1>();
843 sortedFields[i] = enumFields[
index];
849 static int32_t PopCount(uint64_t value)
862 static struct __StaticConstructor__ { __StaticConstructor__(); } s_constructor__;
867TypeCode EnumConverter<T>::s_enumTypeCode;
869bool EnumConverter<T>::s_isSignedEnum;
871bool EnumConverter<T>::s_isFlagsEnum;
873const int32_t EnumConverter<T>::NameCacheSizeSoftLimit;
Class that represents an array data structure. Objects of this class should only be allocated using S...
Definition: array.h:296
A base class for custom attributes. Objects of this class should only be allocated using System::Make...
Definition: attribute.h:16
static SharedPtr< ArrayPool< T > > get_Shared()
Retrieves the process-wide shared pool instance. The instance is created lazily on first access and c...
Definition: array_pool.h:53
static bool IsWhiteSpace(const char_t *str, int idx)
Determines whether the character at the specified index in the specified character buffer is classifi...
Definition: char.h:209
static String ToString(const char_t *obj)
Substitution for C# ToString method to work on any C++ type.
Definition: object_ext.h:103
static auto CoalesceAssign(T0 &value, T1 func) -> T0 &
Implementation of '??=' operator translation.
Definition: object_ext.h:748
Base class that enables using methods available for System.Object class in C#. All non-trivial classe...
Definition: object.h:51
Object()
Creates object. Initializes all internal data structures.
Forward to use within Span class.
Definition: span.h:415
Pointer class to wrap types being allocated on heap. Use it to manage memory for classes inheriting O...
Definition: smart_ptr.h:180
void Clear() const
Clears the contents of the span by setting all elements to default value.
Definition: span.h:387
static StringComparerPtr get_OrdinalIgnoreCase()
Ordinal case-ignoring comparer singleton.
String class used across the library. Is a substitute for C# System.String when translating code....
Definition: string.h:126
String & Append(const char16_t *src, int32_t startIndex, int32_t count)
Puts some characters into string. Changes string size.
Definition: json_encoded_text.h:29
static JsonEncodedText Encode(String value, System::SharedPtr< Encodings::Web::JavaScriptEncoder > encoder=nullptr)
static System::SharedPtr< RegularExpressions::Regex > get_IntegerRegex()
Definition: enum_converter.h:75
void WriteAsPropertyNameCore(System::SharedPtr< Utf8JsonWriter > writer, T value, System::SharedPtr< JsonSerializerOptions > options, bool isWritingExtensionDataProperty) override
Definition: enum_converter.h:406
JsonValueType GetSupportedJsonValueTypes(JsonNumberHandling _) override
Definition: enum_converter.h:454
void SetTemplateWeakPtr(uint32_t argument) override
Set n'th template argument a weak pointer (rather than shared). Allows switching pointers in containe...
Definition: enum_converter.h:472
void Write(System::SharedPtr< Utf8JsonWriter > writer, T value, System::SharedPtr< JsonSerializerOptions > options) override
Definition: enum_converter.h:340
T ReadAsPropertyNameCore(Utf8JsonReader &reader, const System::TypeInfo &typeToConvert, System::SharedPtr< JsonSerializerOptions > options) override
Definition: enum_converter.h:390
T Read(Utf8JsonReader &reader, const System::TypeInfo &typeToConvert, System::SharedPtr< JsonSerializerOptions > options) override
Definition: enum_converter.h:287
EnumConverter(EnumConverterOptions converterOptions, System::SharedPtr< JsonNamingPolicy > namingPolicy, System::SharedPtr< JsonSerializerOptions > options)
Definition: enum_converter.h:236
Definition: json_primitive_converter.h:48
void SetTemplateWeakPtr(uint32_t argument) override
Set n'th template argument a weak pointer (rather than shared). Allows switching pointers in containe...
Definition: json_primitive_converter.h:79
static void ThrowInvalidOperationException_UnsupportedEnumIdentifier(const TypeInfo &enumType, String enumName)
static void ThrowJsonException(String message=nullptr)
Definition: utf8_json_reader.h:78
JsonTokenType get_TokenType()
int32_t get_ValueLength()
int32_t CopyString(Span< uint8_t > utf8Destination)
Represents a particular type and provides information about it.
Definition: type_info.h:109
@ Text
Defines color adjustment information for text.
ReadOnlySpan< T > TrimEnd(const ReadOnlySpan< T > &span, const T &trimElement)
Trims specified element from the end of a typed span.
Definition: memory_extensions.h:3357
Span< T > AsSpan(const ArrayPtr< T > &array, int32_t start=0, int32_t length=-1)
Creates a span from an array.
Definition: memory_extensions.h:2051
int32_t IndexOf(const ReadOnlySpan< T > &span, const ReadOnlySpan< T > &value)
Finds the index of a ReadOnlySpan<T> value in another ReadOnlySpan<T>
Definition: memory_extensions.h:2475
bool SequenceEqual(const ReadOnlySpan< T > &first, const ReadOnlySpan< T > &second)
Determines if two ReadOnlySpans contain identical elements in the same order.
Definition: memory_extensions.h:3145
ReadOnlySpan< T > Trim(const ReadOnlySpan< T > &span, T trimElement)
Trims specified element from both ends of a typed span.
Definition: memory_extensions.h:3293
ReadOnlySpan< T > TrimStart(const ReadOnlySpan< T > &span, const T &trimElement)
Trims specified element from the start of a typed span.
Definition: memory_extensions.h:3401
bool TryAdd(const TCollection &dictionary, const TKey &key, const TValue &value)
Attempts to add the specified key and value to the dictionary, returning true on success.
Definition: json_collection_extensions.h:23
EnumConverterOptions
Definition: enum_converter_options.h:18
JsonValueType
Definition: json_value_type.h:15
JsonNumberHandling
Definition: json_number_handling.h:16
JsonTokenType
Definition: json_token_type.h:12
@ Item
An item such as a node or atomic value.
Definition: db_command.h:9
ValueTuple< Args... > MakeTuple(Args... args)
Creates tuple on stack.
Definition: value_tuple.h:300
SmartPtr< X > MakeSharedPtr(X *p)
Converts raw pointer to smart pointer.
Definition: smart_ptr.h:1640
TypeCode
Represents the type of an object.
Definition: type_code.h:19
@ Int16
An integral type representing signed 16-bit integers with values between -32768 and 32767.
@ SByte
An integral type representing signed 8-bit integers with values between -128 and 127.
@ UInt16
An integral type representing unsigned 16-bit integers with values between 0 and 65535.
@ Byte
An integral type representing unsigned 8-bit integers with values between 0 and 255.
@ UInt64
An integral type representing unsigned 64-bit integers with values between 0 and 18446744073709551615...
@ Int32
An integral type representing signed 32-bit integers with values between -2147483648 and 2147483647.
@ UInt32
An integral type representing unsigned 32-bit integers with values between 0 and 4294967295.
@ Int64
An integral type representing signed 64-bit integers with values between -9223372036854775808 and 922...
@ Ordinal
Use ordinal sort rules.
decltype(Ref(std::declval< T & >())) Ref(const std::reference_wrapper< T > &wrapper)
Wrapper to make sure Ref(std::ref(DynamicWeakPtr)) works.
Definition: dynamic_weak_ptr.h:207
std::enable_if_t< Details::CastType< Source, Result >::None, Result > ExplicitCast(const Source &value)
Casts the source type to the result type using explicit cast. Used when the source and the result typ...
Definition: object_ext.h:960
std::enable_if< IsExceptionWrapper< T >::value, constT & >::type Default()
Returns the reference to the single default-constructed instance of the exception type.
Definition: default.h:16
auto & Get(T &collection, const Index &index)
Implementation for collection[index] expressions.
Definition: index.h:98
Provides methods that perform some operations on values of enum type. This is a static type with no i...
Definition: enum.h:158
static ArrayPtr< String > GetNames()
Returns an array containing names of all members of enumeration E.
Definition: enum.h:291
static bool TryParse(const String &str, E &result)
Tries to convert the specified string into equivalent enum constant.
Definition: enum.h:252
static ArrayPtr< E > GetValues()
Returns an array containing all members of enumeration E.
Definition: enum.h:278