CodePorting.Translator Cs2Cpp
CodePorting.Translator.Cs2Cpp.Framework
json_helpers.h
1#pragma once
2
3#include <system/value_tuple.h>
4#include <system/text/encoding.h>
5#include <system/span.h>
6#include <system/object_ext.h>
7#include <system/memory_extensions.h>
8#include <system/math.h>
9#include <system/icomparable.h>
10#include <system/func.h>
11#include <system/details/stack_array.h>
12#include <system/details/patterns.h>
13#include <system/details/object_builder.h>
14#include <system/constraints.h>
15#include <system/collections/queue.h>
16#include <system/collections/list.h>
17#include <system/collections/ienumerator.h>
18#include <system/collections/icollection.h>
19#include <system/collections/dictionary.h>
20#include <system/array.h>
21#include <cstdint>
22#include <algorithm>
23
24namespace System
25{
26namespace Collections
27{
28namespace Generic
29{
30template <typename> class IEnumerable;
31template <typename> class IEqualityComparer;
32template <typename, typename> class KeyValuePair;
33} // namespace Generic
34} // namespace Collections
35class DateOnly;
36class DateTime;
37enum class DateTimeKind;
38class DateTimeOffset;
39template <typename> class Nullable;
40namespace Text
41{
42namespace Encodings
43{
44namespace Web
45{
46class JavaScriptEncoder;
47} // namespace Web
48} // namespace Encodings
49namespace Json
50{
51enum class JsonTokenType : uint8_t;
52namespace Serialization
53{
54enum class JsonNumberHandling;
55} // namespace Serialization
56class Utf8JsonReader;
57} // namespace Json
58namespace RegularExpressions
59{
60class Regex;
61} // namespace RegularExpressions
62} // namespace Text
63} // namespace System
64
65namespace System {
66
67namespace Text {
68
69namespace Json {
70
72{
73 typedef JsonHelpers ThisType;
74
75private:
76
77 class DateTimeParseData : public System::Object, public System::Details::BoxableObjectBase
78 {
79 typedef DateTimeParseData ThisType;
80 typedef System::Object BaseType;
81
82 typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
83 RTTI_INFO_DECL();
84
85 public:
86
87 int32_t Year;
88 int32_t Month;
89 int32_t Day;
90 bool IsCalendarDateOnly;
91 int32_t Hour;
92 int32_t Minute;
93 int32_t Second;
94 int32_t Fraction;
95 int32_t OffsetHours;
96 int32_t OffsetMinutes;
97
98 bool get_OffsetNegative();
99
100 uint8_t OffsetToken;
101
102 DateTimeParseData();
103
104 };
105
106public:
107
109
110 static ASPOSECPP_SHARED_API ReadOnlySpan<uint8_t> GetUnescapedSpan(Utf8JsonReader& reader);
111 static ASPOSECPP_SHARED_API bool TryAdvanceWithOptionalReadAhead(Utf8JsonReader& reader, bool requiresReadAhead);
112 static ASPOSECPP_SHARED_API bool IsInRangeInclusive(uint32_t value, uint32_t lowerBound, uint32_t upperBound);
113 static ASPOSECPP_SHARED_API bool IsInRangeInclusive(int32_t value, int32_t lowerBound, int32_t upperBound);
114 static ASPOSECPP_SHARED_API bool IsInRangeInclusive(int64_t value, int64_t lowerBound, int64_t upperBound);
115 static ASPOSECPP_SHARED_API bool IsInRangeInclusive(JsonTokenType value, JsonTokenType lowerBound, JsonTokenType upperBound);
116 static ASPOSECPP_SHARED_API bool IsDigit(uint8_t value);
117 static ASPOSECPP_SHARED_API void ReadWithVerify(Utf8JsonReader& reader);
118 static ASPOSECPP_SHARED_API void SkipWithVerify(Utf8JsonReader& reader);
119 static ASPOSECPP_SHARED_API bool TrySkipPartial(Utf8JsonReader& reader);
120 template<typename TValue>
122 {
124 return dictionary->TryGetValue(key, result);
125 }
126
127 template<typename TKey, typename TValue>
129 {
130
131 return System::MakeObject<Collections::Generic::Dictionary<TKey, TValue>>(collection, comparer);
132
133 }
134
135 static ASPOSECPP_SHARED_API void ValidateInt32MaxArrayLength(uint32_t length);
136 static ASPOSECPP_SHARED_API bool AreEqualJsonNumbers(ReadOnlySpan<uint8_t> left, ReadOnlySpan<uint8_t> right);
138 template<typename T, typename TKey>
140 {
141 assert_is_cs_struct(TKey);
142 typedef IComparable<TKey> BaseT_IComparable;
143 assert_is_base_of(BaseT_IComparable, TKey);
144
145 auto arrayCopy = items->ToArray();
146 auto& data = arrayCopy->data();
147 std::stable_sort(data.begin(), data.end(),
148 [&](const T& left, const T& right)
149 {
150 return keySelector(left) < keySelector(right);
151 });
152
153 items->Clear();
154 items->AddRange(arrayCopy);
155 }
156
157 template<typename T>
159 {
160 if (System::IsNull(comparer))
161 {
162 // comparer = Collections::Generic::EqualityComparer<T>::get_Default();
163 }
164
165 // Implements Kahn's algorithm.
166 // Step 1. Traverse and build the graph, labeling each node with an integer.
167
168 auto nodes = System::BuildObject<Collections::Generic::List<T>>().Add(entryNode).Get();
169 // the integer-to-node mapping
170 auto nodeIndex = [&]{ auto tmp_0 = System::MakeObject<Collections::Generic::Dictionary<T, int32_t>>(comparer);
171 tmp_0->idx_set(entryNode, 0); return tmp_0; }();
172 // the node-to-integer mapping
173 auto adjacency = System::MakeObject<Collections::Generic::List<System::SharedPtr<Array<bool>>>>();
174 // the growable adjacency matrix
175 auto childlessQueue = System::MakeObject<Collections::Generic::Queue<int32_t>>();
176 // the queue of nodes without children or whose children have been visited
177
178 for (int32_t i = 0; i < nodes->get_Count(); i++)
179 {
180 T next = nodes->idx_get(i);
181 System::SharedPtr<Collections::Generic::ICollection<T>> children = getChildren(next);
182 int32_t count = children->get_Count();
183
184 if (count == 0)
185 {
186 adjacency->Add(nullptr);
187 // can use null in this row of the adjacency matrix.
188 childlessQueue->Enqueue(i);
189 continue;
190 }
191
192 auto adjacencyRow = System::MakeArray<bool>(System::Math::Max(nodes->get_Count(), count), false);
193 {
194 auto childNode_enumerator = (children)->GetEnumerator();
195 while (childNode_enumerator->MoveNext())
196 {
197 auto&& childNode = childNode_enumerator->get_Current();
198
199 int32_t index;
200 if (!nodeIndex->TryGetValue(childNode, index))
201 {
202 // this is the first time we're encountering this node.
203 // Assign it an index and append it to the maps.
204
205 index = nodes->get_Count();
206 nodeIndex->Add(childNode, index);
207 nodes->Add(childNode);
208 }
209
210 // Grow the adjacency row as appropriate.
211 if (index >= adjacencyRow->get_Length())
212 {
214 }
215
216 // Set the relevant bit in the adjacency row.
217 adjacencyRow[index] = true;
218 }
219 }
220
221 // Append the row to the adjacency matrix.
222 adjacency->Add(adjacencyRow);
223 }
224
225 // Step 2. Build the sorted array, walking from the nodes without children upward.
226 auto sortedNodes = System::MakeArray<T>(nodes->get_Count());
227 int32_t idx = sortedNodes->get_Length();
228
229 do
230 {
231 int32_t nextIndex = childlessQueue->Dequeue();
232 sortedNodes[--idx] = nodes->idx_get(nextIndex);
233
234 // Iterate over the adjacency matrix, removing any occurrence of nextIndex.
235 for (int32_t i = 0; i < adjacency->get_Count(); i++)
236 {
237 System::SharedPtr<System::Array<bool>> childMap = adjacency->idx_get(i);
238 if (childMap != nullptr && nextIndex < childMap->get_Length() && (*childMap)[nextIndex])
239 {
240 (*childMap)[nextIndex] = false;
241
242 if (MemoryExtensions::IndexOf(MemoryExtensions::AsSpan(childMap), true) == -1)
243 {
244 // nextIndex was the last child removed from i, add to queue.
245 childlessQueue->Enqueue(i);
246 }
247 }
248 }
249 } while (childlessQueue->get_Count() > 0);
250
251 return sortedNodes;
252 }
253
254 static ASPOSECPP_SHARED_API bool IsValidDateTimeOffsetParseLength(int32_t length);
255 static ASPOSECPP_SHARED_API bool IsValidUnescapedDateTimeOffsetParseLength(int32_t length);
256 static ASPOSECPP_SHARED_API bool TryParseAsISO(ReadOnlySpan<uint8_t> source, DateTime& value);
257 static ASPOSECPP_SHARED_API bool TryParseAsISO(ReadOnlySpan<uint8_t> source, DateTimeOffset& value);
259 static ASPOSECPP_SHARED_API System::SharedPtr<Array<uint8_t>> EscapeValue(ReadOnlySpan<uint8_t> utf8Value, int32_t firstEscapeIndexVal, System::SharedPtr<Encodings::Web::JavaScriptEncoder> encoder);
260
261private:
262
263 static const String IntegerRegexPattern;
264 static const int32_t IntegerRegexTimeoutMs = 200;
266
267 static ReadOnlySpan<int32_t> get_DaysToMonth365();
268 static ReadOnlySpan<int32_t> get_DaysToMonth366();
269
270 static bool TryAdvanceWithReadAhead(Utf8JsonReader& reader);
271 static bool TryParseDateTimeOffset(ReadOnlySpan<uint8_t> source, JsonHelpers::DateTimeParseData& parseData);
272 static bool TryGetNextTwoDigits(ReadOnlySpan<uint8_t> source, int32_t& value);
273 static bool TryCreateDateTimeOffset(DateTime dateTime, JsonHelpers::DateTimeParseData& parseData, DateTimeOffset& value);
274 static bool TryCreateDateTimeOffset(JsonHelpers::DateTimeParseData& parseData, DateTimeOffset& value);
275 static bool TryCreateDateTimeOffsetInterpretingDataAsLocalTime(JsonHelpers::DateTimeParseData parseData, DateTimeOffset& value);
276 static bool TryCreateDateTime(JsonHelpers::DateTimeParseData parseData, DateTimeKind kind, DateTime& value);
278 static System::SharedPtr<Array<uint8_t>> GetPropertyNameSection(ReadOnlySpan<uint8_t> utf8Value);
279
280public:
281 JsonHelpers() = delete;
282};
283
284} // namespace Json
285} // namespace Text
286} // namespace System
static void Resize(ArrayPtr< Type > &arr, int new_size)
Changes the size of the specified array to the specified value or crates new array with specified siz...
Definition: array.h:1518
Forward declaration of Dictionary class.
Definition: dictionary.h:96
Interface of collection of elements. Objects of this class should only be allocated using System::Mak...
Definition: icollection.h:20
Interface of object providing enumerator on contained elements.
Definition: ienumerable.h:26
Interface providing means to compare two objects for equality. Objects of this class should only be a...
Definition: iequality_comparer.h:18
Pair of key and value. This type should be allocated on stack and passed to functions by value or by ...
Definition: keyvalue_pair.h:20
List forward declaration.
Definition: list.h:129
Represents a specific date and time value on the time continuum. This type should be allocated on sta...
Definition: date_time.h:50
Contains the date and time of day relative to Coordinated Universal Time. Objects of this class shoul...
Definition: date_time_offset.h:16
Function delegate. This type should be allocated on stack and passed to functions by value or by refe...
Definition: func.h:82
Defines a method that compares two objects. Objects of this class should only be allocated using Syst...
Definition: icomparable.h:17
Base class that enables using methods available for System.Object class in C#. All non-trivial classe...
Definition: object.h:51
Pointer class to wrap types being allocated on heap. Use it to manage memory for classes inheriting O...
Definition: smart_ptr.h:180
String class used across the library. Is a substitute for C# System.String when translating code....
Definition: string.h:126
static EncodingPtr get_UTF8()
Gets the standard UTF-8 encoding object.
virtual String GetString(uint8_t *bytes, int byte_count)
Decodes a buffer of bytes into a string.
Definition: json_helpers.h:72
static bool TryAdvanceWithOptionalReadAhead(Utf8JsonReader &reader, bool requiresReadAhead)
static System::SharedPtr< Collections::Generic::Dictionary< TKey, TValue > > CreateDictionaryFromCollection(System::SharedPtr< Collections::Generic::IEnumerable< Collections::Generic::KeyValuePair< TKey, TValue > > > collection, System::SharedPtr< Collections::Generic::IEqualityComparer< TKey > > comparer)
Definition: json_helpers.h:128
static bool IsValidDateTimeOffsetParseLength(int32_t length)
static bool IsDigit(uint8_t value)
static bool TrySkipPartial(Utf8JsonReader &reader)
static void ReadWithVerify(Utf8JsonReader &reader)
static void ValidateInt32MaxArrayLength(uint32_t length)
static System::SharedPtr< Array< T > > TraverseGraphWithTopologicalSort(T entryNode, Func< T, System::SharedPtr< Collections::Generic::ICollection< T > > > getChildren, System::SharedPtr< Collections::Generic::IEqualityComparer< T > > comparer=nullptr)
Definition: json_helpers.h:158
static bool TryParseAsISO(ReadOnlySpan< uint8_t > source, DateTimeOffset &value)
static bool IsInRangeInclusive(uint32_t value, uint32_t lowerBound, uint32_t upperBound)
static bool IsInRangeInclusive(JsonTokenType value, JsonTokenType lowerBound, JsonTokenType upperBound)
static bool TryLookupUtf8Key(System::SharedPtr< Collections::Generic::Dictionary< String, TValue > > dictionary, ReadOnlySpan< uint8_t > utf8Key, TValue &result)
Definition: json_helpers.h:121
static System::SharedPtr< Array< uint8_t > > GetEscapedPropertyNameSection(ReadOnlySpan< uint8_t > utf8Value, System::SharedPtr< Encodings::Web::JavaScriptEncoder > encoder)
static bool TryParseAsISO(ReadOnlySpan< uint8_t > source, DateTime &value)
static bool IsInRangeInclusive(int64_t value, int64_t lowerBound, int64_t upperBound)
static System::SharedPtr< RegularExpressions::Regex > get_IntegerRegex()
static ReadOnlySpan< uint8_t > GetUnescapedSpan(Utf8JsonReader &reader)
static bool AreEqualJsonNumbers(ReadOnlySpan< uint8_t > left, ReadOnlySpan< uint8_t > right)
static void SkipWithVerify(Utf8JsonReader &reader)
static void StableSortByKey(System::SharedPtr< Collections::Generic::List< T > > items, Func< T, TKey > keySelector)
Definition: json_helpers.h:139
static bool IsValidUnescapedDateTimeOffsetParseLength(int32_t length)
static bool IsInRangeInclusive(int32_t value, int32_t lowerBound, int32_t upperBound)
static bool RequiresSpecialNumberHandlingOnWrite(Nullable< Serialization::JsonNumberHandling > handling)
static System::SharedPtr< Array< uint8_t > > EscapeValue(ReadOnlySpan< uint8_t > utf8Value, int32_t firstEscapeIndexVal, System::SharedPtr< Encodings::Web::JavaScriptEncoder > encoder)
Definition: utf8_json_reader.h:78
@ Text
Defines color adjustment information for text.
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
JsonNumberHandling
Definition: json_number_handling.h:16
JsonTokenType
Definition: json_token_type.h:12
Definition: db_command.h:9
DateTimeKind
Enumeration values of which represent the kinds of date and time.
Definition: date_time_kind.h:10
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
static auto Max(T0 val1, T1 val2) -> decltype(val1+val2)
Returns the greatest value out of two numeric ones specified.
Definition: math.h:327