-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathEncoders.cs
More file actions
442 lines (384 loc) · 15.4 KB
/
Encoders.cs
File metadata and controls
442 lines (384 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#nullable enable
using System.Text.Json.Nodes;
namespace AIDotNet.Toon.Internal.Encode
{
/// <summary>
/// Options for encoding TOON format, aligned with TypeScript ResolvedEncodeOptions.
/// </summary>
internal class ResolvedEncodeOptions
{
public int Indent { get; set; } = 2;
public char Delimiter { get; set; } = Constants.COMMA;
public bool LengthMarker { get; set; } = false;
}
/// <summary>
/// Main encoding functions for converting normalized JsonNode values to TOON format.
/// Aligned with TypeScript encode/encoders.ts
/// </summary>
internal static class Encoders
{
// #region Encode normalized JsonValue
/// <summary>
/// Encodes a normalized JsonNode value to TOON format string.
/// </summary>
public static string EncodeValue(JsonNode? value, ResolvedEncodeOptions options)
{
if (Normalize.IsJsonPrimitive(value))
{
return Primitives.EncodePrimitive(value, options.Delimiter);
}
var writer = new LineWriter(options.Indent);
if (Normalize.IsJsonArray(value))
{
EncodeArray(null, (JsonArray)value!, writer, 0, options);
}
else if (Normalize.IsJsonObject(value))
{
EncodeObject((JsonObject)value!, writer, 0, options);
}
return writer.ToString();
}
// #endregion
// #region Object encoding
/// <summary>
/// Encodes a JsonObject as key-value pairs.
/// </summary>
public static void EncodeObject(JsonObject value, LineWriter writer, int depth, ResolvedEncodeOptions options)
{
foreach (var kvp in value)
{
EncodeKeyValuePair(kvp.Key, kvp.Value, writer, depth, options);
}
}
/// <summary>
/// Encodes a single key-value pair.
/// </summary>
public static void EncodeKeyValuePair(string key, JsonNode? value, LineWriter writer, int depth, ResolvedEncodeOptions options)
{
var encodedKey = Primitives.EncodeKey(key);
if (Normalize.IsJsonPrimitive(value))
{
writer.Push(depth, $"{encodedKey}{Constants.COLON} {Primitives.EncodePrimitive(value, options.Delimiter)}");
}
else if (Normalize.IsJsonArray(value))
{
EncodeArray(key, (JsonArray)value!, writer, depth, options);
}
else if (Normalize.IsJsonObject(value))
{
var obj = (JsonObject)value!;
if (obj.Count == 0)
{
// Empty object
writer.Push(depth, $"{encodedKey}{Constants.COLON}");
}
else
{
writer.Push(depth, $"{encodedKey}{Constants.COLON}");
EncodeObject(obj, writer, depth + 1, options);
}
}
}
// #endregion
// #region Array encoding
/// <summary>
/// Encodes a JsonArray with appropriate formatting (inline, tabular, or expanded).
/// </summary>
public static void EncodeArray(
string? key,
JsonArray value,
LineWriter writer,
int depth,
ResolvedEncodeOptions options)
{
if (value.Count == 0)
{
var header = Primitives.FormatHeader(0, key, null, options.Delimiter, options.LengthMarker);
writer.Push(depth, header);
return;
}
// Primitive array
if (Normalize.IsArrayOfPrimitives(value))
{
var formatted = EncodeInlineArrayLine(value, options.Delimiter, key, options.LengthMarker);
writer.Push(depth, formatted);
return;
}
// Array of arrays (all primitives)
if (Normalize.IsArrayOfArrays(value))
{
var allPrimitiveArrays = value.All(item =>
item is JsonArray arr && Normalize.IsArrayOfPrimitives(arr));
if (allPrimitiveArrays)
{
EncodeArrayOfArraysAsListItems(key, value.Cast<JsonArray>().ToList(), writer, depth, options);
return;
}
}
// Array of objects
if (Normalize.IsArrayOfObjects(value))
{
var objects = value.Cast<JsonObject>().ToList();
var header = ExtractTabularHeader(objects);
if (header != null)
{
EncodeArrayOfObjectsAsTabular(key, objects, header, writer, depth, options);
}
else
{
EncodeMixedArrayAsListItems(key, value, writer, depth, options);
}
return;
}
// Mixed array: fallback to expanded format
EncodeMixedArrayAsListItems(key, value, writer, depth, options);
}
// #endregion
// #region Array of arrays (expanded format)
/// <summary>
/// Encodes an array of arrays as list items.
/// </summary>
public static void EncodeArrayOfArraysAsListItems(
string? prefix,
IReadOnlyList<JsonArray> values,
LineWriter writer,
int depth,
ResolvedEncodeOptions options)
{
var header = Primitives.FormatHeader(values.Count, prefix, null, options.Delimiter, options.LengthMarker);
writer.Push(depth, header);
foreach (var arr in values)
{
if (Normalize.IsArrayOfPrimitives(arr))
{
var inline = EncodeInlineArrayLine(arr, options.Delimiter, null, options.LengthMarker);
writer.PushListItem(depth + 1, inline);
}
}
}
/// <summary>
/// Encodes an array as a single inline line with header.
/// </summary>
public static string EncodeInlineArrayLine(
JsonArray values,
char delimiter,
string? prefix = null,
bool lengthMarker = false)
{
var header = Primitives.FormatHeader(values.Count, prefix, null, delimiter, lengthMarker);
if (values.Count == 0)
{
return header;
}
var joinedValue = Primitives.EncodeAndJoinPrimitives(values, delimiter);
return $"{header} {joinedValue}";
}
// #endregion
// #region Array of objects (tabular format)
/// <summary>
/// Encodes an array of objects in tabular format.
/// </summary>
public static void EncodeArrayOfObjectsAsTabular(
string? prefix,
IReadOnlyList<JsonObject> rows,
IReadOnlyList<string> header,
LineWriter writer,
int depth,
ResolvedEncodeOptions options)
{
var formattedHeader = Primitives.FormatHeader(rows.Count, prefix, header, options.Delimiter, options.LengthMarker);
writer.Push(depth, formattedHeader);
WriteTabularRows(rows, header, writer, depth + 1, options);
}
/// <summary>
/// Extracts a uniform header from an array of objects if all objects have the same keys.
/// Returns null if the array cannot be represented in tabular format.
/// </summary>
public static IReadOnlyList<string>? ExtractTabularHeader(IReadOnlyList<JsonObject> rows)
{
if (rows.Count == 0)
return null;
var firstRow = rows[0];
var firstKeys = firstRow.Select(kvp => kvp.Key).ToList();
if (firstKeys.Count == 0)
return null;
if (IsTabularArray(rows, firstKeys))
{
return firstKeys;
}
return null;
}
/// <summary>
/// Checks if an array of objects can be represented in tabular format.
/// All objects must have the same keys and all values must be primitives.
/// </summary>
public static bool IsTabularArray(
IReadOnlyList<JsonObject> rows,
IReadOnlyList<string> header)
{
foreach (var row in rows)
{
var keys = row.Select(kvp => kvp.Key).ToList();
// All objects must have the same keys (but order can differ)
if (keys.Count != header.Count)
return false;
// Check that all header keys exist in the row and all values are primitives
foreach (var key in header)
{
if (!row.ContainsKey(key))
return false;
if (!Normalize.IsJsonPrimitive(row[key]))
return false;
}
}
return true;
}
/// <summary>
/// Writes tabular rows to the writer.
/// </summary>
private static void WriteTabularRows(
IReadOnlyList<JsonObject> rows,
IReadOnlyList<string> header,
LineWriter writer,
int depth,
ResolvedEncodeOptions options)
{
foreach (var row in rows)
{
var values = header.Select(key => row[key]).ToList();
var joinedValue = Primitives.EncodeAndJoinPrimitives(values, options.Delimiter);
writer.Push(depth, joinedValue);
}
}
// #endregion
// #region Array of objects (expanded format)
/// <summary>
/// Encodes a mixed array as list items (expanded format).
/// </summary>
public static void EncodeMixedArrayAsListItems(
string? prefix,
JsonArray items,
LineWriter writer,
int depth,
ResolvedEncodeOptions options)
{
var header = Primitives.FormatHeader(items.Count, prefix, null, options.Delimiter, options.LengthMarker);
writer.Push(depth, header);
foreach (var item in items)
{
EncodeListItemValue(item, writer, depth + 1, options);
}
}
/// <summary>
/// Encodes an object as a list item with special formatting for the first property.
/// </summary>
public static void EncodeObjectAsListItem(JsonObject obj, LineWriter writer, int depth, ResolvedEncodeOptions options)
{
var keys = obj.Select(kvp => kvp.Key).ToList();
if (keys.Count == 0)
{
writer.Push(depth, Constants.LIST_ITEM_MARKER.ToString());
return;
}
// First key-value on the same line as "- "
var firstKey = keys[0];
var encodedKey = Primitives.EncodeKey(firstKey);
var firstValue = obj[firstKey];
if (Normalize.IsJsonPrimitive(firstValue))
{
writer.PushListItem(depth, $"{encodedKey}{Constants.COLON} {Primitives.EncodePrimitive(firstValue, options.Delimiter)}");
}
else if (Normalize.IsJsonArray(firstValue))
{
var arr = (JsonArray)firstValue!;
if (Normalize.IsArrayOfPrimitives(arr))
{
// Inline format for primitive arrays
var formatted = EncodeInlineArrayLine(arr, options.Delimiter, firstKey, options.LengthMarker);
writer.PushListItem(depth, formatted);
}
else if (Normalize.IsArrayOfObjects(arr))
{
// Check if array of objects can use tabular format
var objects = arr.Cast<JsonObject>().ToList();
var header = ExtractTabularHeader(objects);
if (header != null)
{
// Tabular format for uniform arrays of objects
var formattedHeader = Primitives.FormatHeader(arr.Count, firstKey, header, options.Delimiter, options.LengthMarker);
writer.PushListItem(depth, formattedHeader);
WriteTabularRows(objects, header, writer, depth + 1, options);
}
else
{
// Fall back to list format for non-uniform arrays of objects
writer.PushListItem(depth, $"{encodedKey}{Constants.OPEN_BRACKET}{arr.Count}{Constants.CLOSE_BRACKET}{Constants.COLON}");
foreach (var item in arr)
{
if (item is JsonObject itemObj)
{
EncodeObjectAsListItem(itemObj, writer, depth + 1, options);
}
}
}
}
else
{
// Complex arrays on separate lines (array of arrays, etc.)
writer.PushListItem(depth, $"{encodedKey}{Constants.OPEN_BRACKET}{arr.Count}{Constants.CLOSE_BRACKET}{Constants.COLON}");
// Encode array contents at depth + 1
foreach (var item in arr)
{
EncodeListItemValue(item, writer, depth + 1, options);
}
}
}
else if (Normalize.IsJsonObject(firstValue))
{
var nestedObj = (JsonObject)firstValue!;
if (nestedObj.Count == 0)
{
writer.PushListItem(depth, $"{encodedKey}{Constants.COLON}");
}
else
{
writer.PushListItem(depth, $"{encodedKey}{Constants.COLON}");
EncodeObject(nestedObj, writer, depth + 2, options);
}
}
// Remaining keys on indented lines
for (int i = 1; i < keys.Count; i++)
{
var key = keys[i];
EncodeKeyValuePair(key, obj[key], writer, depth + 1, options);
}
}
// #endregion
// #region List item encoding helpers
/// <summary>
/// Encodes a value as a list item.
/// </summary>
private static void EncodeListItemValue(
JsonNode? value,
LineWriter writer,
int depth,
ResolvedEncodeOptions options)
{
if (Normalize.IsJsonPrimitive(value))
{
writer.PushListItem(depth, Primitives.EncodePrimitive(value, options.Delimiter));
}
else if (Normalize.IsJsonArray(value) && Normalize.IsArrayOfPrimitives((JsonArray)value!))
{
var arr = (JsonArray)value!;
var inline = EncodeInlineArrayLine(arr, options.Delimiter, null, options.LengthMarker);
writer.PushListItem(depth, inline);
}
else if (Normalize.IsJsonObject(value))
{
EncodeObjectAsListItem((JsonObject)value!, writer, depth, options);
}
}
// #endregion
}
}