CodePorting.Translator Cs2Cpp
CodePorting.Translator.Cs2Cpp.Framework
enum_converter.h
1#pragma once
2
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>
30#include <cstdint>
31#include <type_traits>
32
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"
48
49namespace System
50{
51namespace Text
52{
53namespace Json
54{
55namespace Serialization
56{
57enum class JsonNumberHandling;
58} // namespace Serialization
59} // namespace Json
60} // namespace Text
61} // namespace System
62
63namespace System {
64
65namespace Text {
66
67namespace Json {
68
69namespace Serialization {
70
71namespace Converters {
72
73template<typename T>
75{
78
79 typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
80 RTTI_INFO_TEMPLATE_CLASS(ThisType, ThisTypeBaseTypesInfo);
81
82 template<typename FT0> friend class EnumConverter;
83
84private:
85
86 enum class EnumFieldNameKind
87 {
88 Default = 0,
89 NamingPolicy = 1,
90 Attribute = 2
91 };
92
93private:
94
95 class EnumFieldInfo final : public System::Object
96 {
97 typedef EnumFieldInfo ThisType;
98 typedef System::Object BaseType;
99
100 typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
101 RTTI_INFO_TEMPLATE_CLASS(ThisType, ThisTypeBaseTypesInfo);
102
103 template<typename FT0> friend class EnumConverter;
104
105 public:
106
107 EnumFieldNameKind get_Kind()
108 {
109 return pr_Kind;
110 }
111
112 uint64_t get_Key()
113 {
114 return pr_Key;
115 }
116
117 String get_OriginalName()
118 {
119 return pr_OriginalName;
120 }
121
122 String get_JsonName()
123 {
124 return pr_JsonName;
125 }
126
127 void AppendConflictingField(typename System::SharedPtr<EnumFieldInfo> other)
128 {
129
130 static auto ConflictsWith = [](typename System::SharedPtr<EnumFieldInfo> current, typename System::SharedPtr<EnumFieldInfo> other) -> bool
131 {
132 // The default name matches everything case-insensitively.
133 if (current->get_Kind() == EnumFieldNameKind::Default)
134 {
135 return true;
136 }
137
138 // current matches case-sensitively since it's not the default name.
139 // other matches case-insensitively, so it matches more than current.
140 if (other->get_Kind() == EnumFieldNameKind::Default)
141 {
142 return false;
143 }
144
145 // Both are case-sensitive so they need to be identical.
146 return current->get_JsonName().Equals(other->get_JsonName(), System::StringComparison::Ordinal);
147 };
148
149 if (ConflictsWith(System::MakeSharedPtr(this), other))
150 {
151 // Silently discard if the preceding entry is the default or has identical name.
152 return;
153 }
154
155 System::SharedPtr<Collections::Generic::List<System::SharedPtr<EnumFieldInfo>>> conflictingFields = System::ObjectExt::CoalesceAssign(_conflictingFields, [&]{return System::BuildObject<Collections::Generic::List<System::SharedPtr<EnumFieldInfo>>>().Get();});
156
157 // Walk the existing list to ensure we do not add duplicates.
158 {
159 auto conflictingField_enumerator = (conflictingFields)->GetEnumerator();
160 while (conflictingField_enumerator->MoveNext())
161 {
162 auto&& conflictingField = conflictingField_enumerator->get_Current();
163
164 if (ConflictsWith(conflictingField, other))
165 {
166 return;
167 }
168 }
169 }
170
171 conflictingFields->Add(other);
172 }
173
174 System::SharedPtr<EnumFieldInfo> GetMatchingField(ReadOnlySpan<char16_t> input)
175 {
176
177 if (get_Kind() == EnumFieldNameKind::Default || MemoryExtensions::SequenceEqual(input, MemoryExtensions::AsSpan(get_JsonName())))
178 {
179 // Default enum names use case insensitive parsing so are always a match.
180 return System::MakeSharedPtr(this);
181 }
182
183 if (true)
184 {
185
186 {
187 auto matchingField_enumerator = (_conflictingFields)->GetEnumerator();
188 while (matchingField_enumerator->MoveNext())
189 {
190 auto&& matchingField = matchingField_enumerator->get_Current();
191
192 if (matchingField->get_Kind() == EnumFieldNameKind::Default || MemoryExtensions::SequenceEqual(input, MemoryExtensions::AsSpan(matchingField->get_JsonName())))
193 {
194 return matchingField;
195 }
196 }
197 }
198 }
199
200 return nullptr;
201 }
202
203 EnumFieldInfo(uint64_t key, EnumFieldNameKind kind, String originalName, String jsonName)
204 : pr_Kind(kind), pr_Key(key), pr_OriginalName(originalName), pr_JsonName(jsonName)
205 {
206 }
207
208 protected:
209
210 virtual ~EnumFieldInfo()
211 {
212 }
213
214 #ifdef ASPOSE_GET_SHARED_MEMBERS
215 void GetSharedMembers(System::Object::shared_members_type& result) const override
216 {
217 Object::GetSharedMembers(result);
218
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);
221 }
222 #endif
223
224 private:
225
227 EnumFieldNameKind pr_Kind;
228 uint64_t pr_Key;
229 String pr_OriginalName;
230 String pr_JsonName;
231
232 };
233
234public:
235
237 : _converterOptions((EnumConverterOptions)0)
238 {
239 System::Details::ThisProtector __local_self_ref(this);
240
241 s_enumTypeCode = GetEnumTypeCode();
242 s_isSignedEnum = std::is_signed<typename std::underlying_type<T>::type>::value;
243 s_isFlagsEnum = false;
244
245 _converterOptions = converterOptions;
246 _namingPolicy = namingPolicy;
247 _enumFieldInfo = ResolveEnumFields(namingPolicy);
248 _enumFieldInfoIndex = System::MakeObject<Collections::Generic::Dictionary<String, System::SharedPtr<EnumFieldInfo>>>(System::StringComparer::get_OrdinalIgnoreCase());
249
250 _nameCacheForWriting = System::MakeObject<Collections::Concurrent::ConcurrentDictionary<uint64_t, JsonEncodedText>>();
251 _nameCacheForReading = System::MakeObject<Collections::Concurrent::ConcurrentDictionary<String, uint64_t>>();
252
253 System::SharedPtr<Encodings::Web::JavaScriptEncoder> encoder = options->get_Encoder();
254
255 auto AddToEnumFieldIndex = [&](System::SharedPtr<EnumFieldInfo> fieldInfo)
256 {
257 if (!JsonCollectionExtensions::TryAdd(_enumFieldInfoIndex, fieldInfo->get_JsonName(), fieldInfo))
258 {
259 // We have a casing conflict, append field to the existing entry.
260 System::SharedPtr<EnumFieldInfo> existingFieldInfo = _enumFieldInfoIndex->idx_get(fieldInfo->get_JsonName());
261 existingFieldInfo->AppendConflictingField(fieldInfo);
262 }
263 };
264 for (System::SharedPtr<EnumFieldInfo> fieldInfo : _enumFieldInfo)
265 {
266 AddToEnumFieldIndex(fieldInfo);
267
268 JsonEncodedText encodedName = System::Text::Json::JsonEncodedText::Encode(fieldInfo->get_JsonName(), encoder);
269 _nameCacheForWriting->TryAdd(fieldInfo->get_Key(), encodedName);
270 _nameCacheForReading->TryAdd(fieldInfo->get_JsonName(), fieldInfo->get_Key());
271 }
272
273 if (!(namingPolicy == nullptr))
274 {
275 // Additionally populate the field index with the default names of fields that used a naming policy.
276 // This is done to preserve backward compat: default names should still be recognized by the parser.
277 for (System::SharedPtr<EnumFieldInfo> fieldInfo : _enumFieldInfo)
278 {
279 if (fieldInfo->get_Kind() == EnumFieldNameKind::NamingPolicy)
280 {
281 AddToEnumFieldIndex(System::MakeObject<EnumFieldInfo>(fieldInfo->get_Key(), System::Text::Json::Serialization::Converters::EnumConverter<T>::EnumFieldNameKind::Default, fieldInfo->get_OriginalName(), fieldInfo->get_OriginalName()));
282 }
283 }
284 }
285 }
286
287 T Read(Utf8JsonReader& reader, const System::TypeInfo& typeToConvert, System::SharedPtr<JsonSerializerOptions> options) override
288 {
289 ASPOSE_UNUSED(typeToConvert);
290 ASPOSE_UNUSED(options);
291 const JsonTokenType& switch_value_0 = reader.get_TokenType();
292 if (switch_value_0 == System::Text::Json::JsonTokenType::String)
293 {
294 T result;
295 if (TryParseEnumFromString(System::Ref(reader), result))
296 {
297 return result;
298 }
299 }
300 else if (switch_value_0 == System::Text::Json::JsonTokenType::Number)
301 {
302 if (s_enumTypeCode == System::TypeCode::Int32)
303 {
304 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetInt32()));
305 }
306 else if (s_enumTypeCode == System::TypeCode::UInt32)
307 {
308 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetUInt32()));
309 }
310 else if (s_enumTypeCode == System::TypeCode::Int64)
311 {
312 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetInt64()));
313 }
314 else if (s_enumTypeCode == System::TypeCode::UInt64)
315 {
316 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetUInt64()));
317 }
318 else if (s_enumTypeCode == System::TypeCode::Byte)
319 {
320 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetByte()));
321 }
322 else if (s_enumTypeCode == System::TypeCode::SByte)
323 {
324 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetSByte()));
325 }
326 else if (s_enumTypeCode == System::TypeCode::Int16)
327 {
328 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetInt16()));
329 }
330 else if (s_enumTypeCode == System::TypeCode::UInt16)
331 {
332 return System::ExplicitCast<T>(System::ExplicitCast<System::Object>(reader.GetUInt16()));
333 }
334 }
335
337 return System::Default<T>();
338 }
339
341 {
342 EnumConverterOptions converterOptions = _converterOptions;
344 {
345 uint64_t key = ConvertToUInt64(value);
346
347 JsonEncodedText formatted;
348 if (_nameCacheForWriting->TryGetValue(key, formatted))
349 {
350 writer->WriteStringValue(formatted);
351 return;
352 }
353
354 if (IsDefinedValueOrCombinationOfValues(key))
355 {
356
357 String stringValue = FormatEnumAsString(key, value, nullptr);
358 if (_nameCacheForWriting->get_Count() < NameCacheSizeSoftLimit)
359 {
360 formatted = System::Text::Json::JsonEncodedText::Encode(stringValue, options->get_Encoder());
361 writer->WriteStringValue(formatted);
362 _nameCacheForWriting->TryAdd(key, formatted);
363 }
364 else
365 {
366 // We also do not create a JsonEncodedText instance here because passing the string
367 // directly to the writer is cheaper than creating one and not caching it for reuse.
368 writer->WriteStringValue(stringValue);
369 }
370
371 return;
372 }
373 }
374
376 {
378 }
379
380 if (s_isSignedEnum)
381 {
382 writer->WriteNumberValue(ConvertToInt64(value));
383 }
384 else
385 {
386 writer->WriteNumberValue(ConvertToUInt64(value));
387 }
388 }
389
391 {
392 ASPOSE_UNUSED(typeToConvert);
393 ASPOSE_UNUSED(options);
394 // NB JsonSerializerOptions.DictionaryKeyPolicy is ignored on deserialization.
395 // This is true for all converters that implement dictionary key serialization.
396
397 T result;
398 if (!TryParseEnumFromString(System::Ref(reader), result))
399 {
401 }
402
403 return result;
404 }
405
406 void WriteAsPropertyNameCore(System::SharedPtr<Utf8JsonWriter> writer, T value, System::SharedPtr<JsonSerializerOptions> options, bool isWritingExtensionDataProperty) override
407 {
408 ASPOSE_UNUSED(isWritingExtensionDataProperty);
409 System::SharedPtr<JsonNamingPolicy> dictionaryKeyPolicy = options != nullptr ? options->get_DictionaryKeyPolicy() : nullptr;
410 if (dictionaryKeyPolicy == _namingPolicy)
411 {
412 dictionaryKeyPolicy = nullptr;
413 }
414 uint64_t key = ConvertToUInt64(value);
415
416 JsonEncodedText formatted;
417 if (dictionaryKeyPolicy == nullptr && _nameCacheForWriting->TryGetValue(key, formatted))
418 {
419 writer->WritePropertyName(formatted);
420 return;
421 }
422
423 if (IsDefinedValueOrCombinationOfValues(key))
424 {
425
426 String stringValue = FormatEnumAsString(key, value, dictionaryKeyPolicy);
427 if (dictionaryKeyPolicy == nullptr && _nameCacheForWriting->get_Count() < NameCacheSizeSoftLimit)
428 {
429 // Only attempt to cache if there is no dictionary key policy.
430 formatted = System::Text::Json::JsonEncodedText::Encode(stringValue, options->get_Encoder());
431 writer->WritePropertyName(formatted);
432 _nameCacheForWriting->TryAdd(key, formatted);
433 }
434 else
435 {
436 // We also do not create a JsonEncodedText instance here because passing the string
437 // directly to the writer is cheaper than creating one and not caching it for reuse.
438 writer->WritePropertyName(stringValue);
439 }
440
441 return;
442 }
443
444 if (s_isSignedEnum)
445 {
446 writer->WritePropertyName(ConvertToInt64(value));
447 }
448 else
449 {
450 writer->WritePropertyName(key);
451 }
452 }
453
455 {
456 ASPOSE_UNUSED(_);
457 EnumConverterOptions converterOptions = _converterOptions;
460
461 if (allowsString && allowsNumber)
462 {
464 }
465 if (allowsString)
466 {
468 }
470 }
471
472 void SetTemplateWeakPtr(uint32_t argument) override
473 {
474 switch (argument)
475 {
476 case 0:
478 break;
479
480 }
481 }
482
483protected:
484
485 #ifdef ASPOSE_GET_SHARED_MEMBERS
486 void GetSharedMembers(System::Object::shared_members_type& result) const override
487 {
489
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);
496 }
497 #endif
498
499private:
500
501 static TypeCode s_enumTypeCode;
502 static bool s_isSignedEnum;
503 static bool s_isFlagsEnum;
504 EnumConverterOptions _converterOptions;
510 static const int32_t NameCacheSizeSoftLimit = 64;
511
512 bool TryParseEnumFromString(Utf8JsonReader& reader, T& result)
513 {
514
515 int32_t bufferLength = reader.get_ValueLength();
517 bool success;
518
519 System::Details::StackArray<char16_t, System::Text::Json::JsonConstants::StackallocCharThreshold> array_0;
520 Span<char16_t> charBuffer = bufferLength <= System::Text::Json::JsonConstants::StackallocCharThreshold ? array_0 : Span<char16_t>::to_Span((rentedBuffer = Buffers::ArrayPool<char16_t>::get_Shared()->Rent(bufferLength)));
521
522 int32_t charsWritten = reader.CopyString(charBuffer);
523 charBuffer = charBuffer.Slice(0, charsWritten);
526 uint64_t key;
527 if (lookup->TryGetValue(source, key))
528 {
529 result = ConvertFromUInt64(key);
530 success = true;
531 goto End;
532 }
533
535 {
536 // We found an integer that is not an enum field name.
538 {
539 success = System::Enum<T>::TryParse(source, result);
540 }
541 else
542 {
543 result = System::Default<T>();
544 success = false;
545 }
546 }
547 else
548 {
549 success = TryParseNamedEnum(source, result);
550 }
551
552 if (success && _nameCacheForReading->get_Count() < NameCacheSizeSoftLimit)
553 {
554 lookup->TryAdd(source, ConvertToUInt64(result));
555 }
556
557 End:
558 if (!(rentedBuffer == nullptr))
559 {
560 charBuffer.Clear();
561 Buffers::ArrayPool<char16_t>::get_Shared()->Return(rentedBuffer);
562 }
563
564 return success;
565 }
566
567 bool TryParseNamedEnum(String source, T& result)
568 {
570 ReadOnlySpan<char16_t> rest = MemoryExtensions::AsSpan(source);
571 uint64_t key = 0;
572
573 do
574 {
575 ReadOnlySpan<char16_t> next;
576 int32_t i = MemoryExtensions::IndexOf(rest, u',');
577 if (i == -1)
578 {
579 next = rest;
580 rest = System::Default<System::ReadOnlySpan<char16_t>>();
581 }
582 else
583 {
584 next = MemoryExtensions::TrimEnd(rest.Slice(0, i));
585 rest = MemoryExtensions::TrimStart(rest.Slice(i + 1));
586 }
587
588 System::SharedPtr<EnumFieldInfo> firstResult, match;
589 if (lookup->TryGetValue(System::ObjectExt::ToString(next), firstResult) && System::Is<EnumFieldInfo>(firstResult->GetMatchingField(next), match))
590 {
591 key |= match->get_Key();
592 continue;
593 }
594
595 result = System::Default<T>();
596 return false;
597 } while (!rest.get_IsEmpty());
598
599 result = ConvertFromUInt64(key);
600 return true;
601 }
602
603 static TypeCode GetEnumTypeCode()
604 {
605 typedef typename std::underlying_type<T>::type Underlying;
606 if (sizeof(Underlying) == 1)
607 {
608 return std::is_signed<Underlying>::value ? System::TypeCode::SByte : System::TypeCode::Byte;
609 }
610 if (sizeof(Underlying) == 2)
611 {
612 return std::is_signed<Underlying>::value ? System::TypeCode::Int16 : System::TypeCode::UInt16;
613 }
614 if (sizeof(Underlying) == 4)
615 {
616 return std::is_signed<Underlying>::value ? System::TypeCode::Int32 : System::TypeCode::UInt32;
617 }
618 return std::is_signed<Underlying>::value ? System::TypeCode::Int64 : System::TypeCode::UInt64;
619 }
620
621 static uint64_t ConvertToUInt64(T value)
622 {
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)) :
626 s_enumTypeCode == System::TypeCode::UInt64 ? System::ExplicitCast<uint64_t>(System::ExplicitCast<System::Object>(value)) :
627 s_enumTypeCode == System::TypeCode::Int16 ? (uint64_t)System::ExplicitCast<int16_t>(System::ExplicitCast<System::Object>(value)) :
628 s_enumTypeCode == System::TypeCode::UInt16 ? System::ExplicitCast<uint16_t>(System::ExplicitCast<System::Object>(value)) :
629 s_enumTypeCode == System::TypeCode::SByte ? (uint64_t)System::ExplicitCast<int8_t>(System::ExplicitCast<System::Object>(value)) :
631 }
632
633 static int64_t ConvertToInt64(T value)
634 {
635
636 return s_enumTypeCode == System::TypeCode::Int32 ? System::ExplicitCast<int32_t>(System::ExplicitCast<System::Object>(value)) :
637 s_enumTypeCode == System::TypeCode::Int64 ? System::ExplicitCast<int64_t>(System::ExplicitCast<System::Object>(value)) :
638 s_enumTypeCode == System::TypeCode::Int16 ? System::ExplicitCast<int16_t>(System::ExplicitCast<System::Object>(value)) :
640 }
641
642 static T ConvertFromUInt64(uint64_t value)
643 {
644 return s_enumTypeCode == System::TypeCode::Int32 ? System::ExplicitCast<T>(System::ExplicitCast<System::Object>((int32_t)value)) :
645 s_enumTypeCode == System::TypeCode::UInt32 ? System::ExplicitCast<T>(System::ExplicitCast<System::Object>((uint32_t)value)) :
646 s_enumTypeCode == System::TypeCode::Int64 ? System::ExplicitCast<T>(System::ExplicitCast<System::Object>((int64_t)value)) :
648 s_enumTypeCode == System::TypeCode::Int16 ? System::ExplicitCast<T>(System::ExplicitCast<System::Object>((int16_t)value)) :
649 s_enumTypeCode == System::TypeCode::UInt16 ? System::ExplicitCast<T>(System::ExplicitCast<System::Object>((uint16_t)value)) :
650 s_enumTypeCode == System::TypeCode::SByte ? System::ExplicitCast<T>(System::ExplicitCast<System::Object>((int8_t)value)) :
652 }
653
654 // Using statement is translated using System::Details::DisposeGuard class which may store exception and then throw from destructor.
655 // We block the warnings related as these are false alarms (the exception, if caught, will be re-thrown from the destructor).
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"
664 #endif
665 String FormatEnumAsString(uint64_t key, T value, System::SharedPtr<JsonNamingPolicy> dictionaryKeyPolicy)
666 {
667
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.");
669
670 if (s_isFlagsEnum)
671 {
672 System::Details::StackArray<char16_t, System::Text::Json::JsonConstants::StackallocCharThreshold> array_0;
673 ValueStringBuilder sb = ValueStringBuilder(array_0);
674
675 uint64_t remainingBits = key;
676 for (System::SharedPtr<EnumFieldInfo> enumField : _enumFieldInfo)
677 {
678 uint64_t fieldKey = enumField->get_Key();
679 if (fieldKey == 0 ? key == 0 : (remainingBits & fieldKey) == fieldKey)
680 {
681 remainingBits &= ~fieldKey;
682 String name = !(dictionaryKeyPolicy == nullptr) ? ResolveAndValidateJsonName(enumField->get_OriginalName(), dictionaryKeyPolicy, enumField->get_Kind()) : enumField->get_JsonName();
683
684 if (sb.get_Length() > 0)
685 {
686 sb.Append(u", ");
687 }
688
689 sb.Append(name);
690
691 if (remainingBits == 0)
692 {
693 break;
694 }
695 }
696 }
697
699 }
700 else
701 {
702
703 for (System::SharedPtr<EnumFieldInfo> enumField : _enumFieldInfo)
704 {
705 // Search for an exact match and apply the key policy.
706 if (enumField->get_Key() == key)
707 {
708 return ResolveAndValidateJsonName(enumField->get_OriginalName(), dictionaryKeyPolicy, enumField->get_Kind());
709 }
710 }
711
712 CODEPORTING_DEBUG_FAIL1(u"should not have been reached.");
713 return nullptr;
714 }
715 }
716 #if defined(__MSVC__)
717 #pragma warning( pop )
718 #elif defined(__GNUC__)
719 #pragma GCC diagnostic pop
720 #endif
721
722 bool IsDefinedValueOrCombinationOfValues(uint64_t key)
723 {
724 if (s_isFlagsEnum)
725 {
726 uint64_t remainingBits = key;
727
728 for (System::SharedPtr<EnumFieldInfo> fieldInfo : _enumFieldInfo)
729 {
730 uint64_t fieldKey = fieldInfo->get_Key();
731 if (fieldKey == 0 ? key == 0 : (remainingBits & fieldKey) == fieldKey)
732 {
733 remainingBits &= ~fieldKey;
734
735 if (remainingBits == 0)
736 {
737 return true;
738 }
739 }
740 }
741
742 return false;
743 }
744 else
745 {
746 for (System::SharedPtr<EnumFieldInfo> fieldInfo : _enumFieldInfo)
747 {
748 if (fieldInfo->get_Key() == key)
749 {
750 return true;
751 }
752 }
753
754 return false;
755 }
756 }
757
759 {
760
763
764 // Enum member name overrides applied through attributes are not supported for C++ enum
765 // class types; fall back to the enum field names produced by EnumMetaInfo.
767
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++)
770 {
771 String originalName = names[i];
772 T value = values[i];
773 uint64_t key = ConvertToUInt64(value);
774 EnumFieldNameKind kind;
775
776 String attributeName;
777 if (!(enumMemberAttributes == nullptr) && enumMemberAttributes->TryGetValue(originalName, attributeName))
778 {
779 originalName = attributeName;
781 }
782 else
783 {
785 }
786
787 String jsonName = ResolveAndValidateJsonName(originalName, namingPolicy, kind);
788 enumFields[i] = System::MakeObject<EnumFieldInfo>(key, kind, originalName, jsonName);
789 }
790
791 if (s_isFlagsEnum)
792 {
793 // Perform topological sort for flags enums to ensure values that are supersets of other values come first.
794 // This is important for flags enums to ensure proper parsing and formatting.
795 enumFields = TopologicalSortEnumFields(enumFields);
796 }
797
798 return enumFields;
799 }
800
801 static String ResolveAndValidateJsonName(String name, System::SharedPtr<JsonNamingPolicy> namingPolicy, EnumFieldNameKind kind)
802 {
804 {
805 // Do not apply a naming policy to names that are explicitly set via attributes.
806 // This is consistent with JsonPropertyNameAttribute semantics.
807 name = namingPolicy->ConvertName(name);
808 }
809
810 if (name == nullptr || (name.get_Length() > 0 && (System::Char::IsWhiteSpace(name[0]) || System::Char::IsWhiteSpace(name[name.get_Length() - 1]))) || (s_isFlagsEnum && (name.get_Length() == 0 || name.Contains(u','))))
811 {
812 // Reject null strings or strings with leading or trailing whitespace.
813 // In the case of flags additionally reject empty strings or strings containing commas,
814 // both of which would introduce ambiguity in flag value parsing and formatting.
816 }
817
818 return name;
819 }
820
822 {
823 if (enumFields->get_Length() <= 1)
824 {
825 return enumFields;
826 }
827
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++)
830 {
831 // We want values with more bits set to come first so negate the pop count.
832 // Keep the index as a second comparand so that sorting stability is preserved.
833 indices[i] = System::MakeTuple(-PopCount(enumFields[i]->get_Key()), i);
834 }
835
837
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++)
840 {
841 // extract the index from the sorted tuple
842 int32_t index = indices[i].template Item<1/*index*/>();
843 sortedFields[i] = enumFields[index];
844 }
845
846 return sortedFields;
847 }
848
849 static int32_t PopCount(uint64_t value)
850 {
851
852 int32_t count = 0;
853 while (value != 0)
854 {
855 value &= value - 1;
856 count++;
857 }
858 return count;
859
860 }
861
862 static struct __StaticConstructor__ { __StaticConstructor__(); } s_constructor__;
863
864};
865
866template<typename T>
867TypeCode EnumConverter<T>::s_enumTypeCode;
868template<typename T>
869bool EnumConverter<T>::s_isSignedEnum;
870template<typename T>
871bool EnumConverter<T>::s_isFlagsEnum;
872template<typename T>
873const int32_t EnumConverter<T>::NameCacheSizeSoftLimit;
874
875} // namespace Converters
876} // namespace Serialization
877} // namespace Json
878} // namespace Text
879} // namespace System
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()
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
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
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.
@ End
End of the stream.
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