Path: redb/redb.Core/Utils/RedbKeySerializer.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Utils/RedbKeySerializer.cs ---- using System; using System.Globalization; using System.Text; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; namespace redb.Core.Utils; /// /// Serializes and deserializes Dictionary keys to/from _array_index (text) storage. /// Simple keys (string, int, Guid, etc.) are serialized directly. /// Complex keys (Tuple, custom classes) are serialized to Base64-encoded JSON. /// public static class RedbKeySerializer { /// /// Serialize key to _array_index text value /// /// Type of key /// Key to serialize /// String representation for _array_index column public static string Serialize(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key), "Dictionary key cannot be null"); return SerializeObject(key, typeof(TKey)); } /// /// Serialize key to _array_index text value (non-generic version) /// /// Key to serialize /// Type of key /// String representation for _array_index column public static string SerializeObject(object key, Type keyType) { if (key == null) throw new ArgumentNullException(nameof(key), "Dictionary key cannot be null"); // String types - direct if (keyType == typeof(string)) return (string)key; if (keyType == typeof(char)) return ((char)key).ToString(); // Integer types - to string if (keyType == typeof(long)) return ((long)key).ToString(CultureInfo.InvariantCulture); if (keyType == typeof(int)) return ((int)key).ToString(CultureInfo.InvariantCulture); if (keyType == typeof(short)) return ((short)key).ToString(CultureInfo.InvariantCulture); if (keyType == typeof(byte)) return ((byte)key).ToString(CultureInfo.InvariantCulture); // Floating point - invariant culture if (keyType == typeof(double)) return ((double)key).ToString("G17", CultureInfo.InvariantCulture); if (keyType == typeof(float)) return ((float)key).ToString("G9", CultureInfo.InvariantCulture); if (keyType == typeof(decimal)) return ((decimal)key).ToString(CultureInfo.InvariantCulture); // Boolean if (keyType == typeof(bool)) return ((bool)key) ? "true" : "false"; // DateTime types - ISO 8601 if (keyType == typeof(DateTime)) return ((DateTime)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(DateTimeOffset)) return ((DateTimeOffset)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(DateOnly)) return ((DateOnly)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(TimeOnly)) return ((TimeOnly)key).ToString("O", CultureInfo.InvariantCulture); if (keyType == typeof(TimeSpan)) return ((TimeSpan)key).ToString("c", CultureInfo.InvariantCulture); // Guid if (keyType == typeof(Guid)) return ((Guid)key).ToString(); // Byte array - Base64 if (keyType == typeof(byte[])) return Convert.ToBase64String((byte[])key); // Enum - as string name if (keyType.IsEnum) return key.ToString()!; // Complex keys (Tuple, custom classes) - Base64-encoded JSON // Base64 avoids escaping issues when key is used in JSON facet filters var json = JsonSerializer.Serialize(key, keyType, KeyJsonOptions); return Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); } /// /// The options for the JSON of a complex key: the defaults plus . /// System.Text.Json writes no fields, and a ValueTuple has nothing but fields: without the converter a ValueTuple /// anywhere in a key (the key itself, a field of it, the Rest of a tuple of eight or more fields, an item of a /// Tuple<>, a property of a key class) was written as {}, and keys differing only there gave one /// text. A key with no ValueTuple in it gives the text it always gave. /// private static readonly JsonSerializerOptions KeyJsonOptions = new() { Converters = { new ValueTupleFieldsConverterFactory() } }; /// A ValueTuple of any arity, the one-field ValueTuple<T1> that ends a Rest chain included. private static bool IsValueTuple(Type type) => type.IsValueType && type.IsGenericType && type.FullName?.StartsWith("System.ValueTuple`", StringComparison.Ordinal) == true; /// /// Writes a ValueTuple as the object of its fields by name, each value by its runtime type, the way a /// Dictionary<string, object?> of the fields was written before, so a tuple of up to seven fields with no /// nested tuple keeps its text. Reads each field by its declared type; a field missing from the text, or a stored /// {}, reads as the field's default, as it did before. /// private sealed class ValueTupleFieldsConverterFactory : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) => IsValueTuple(typeToConvert); public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => (JsonConverter)Activator.CreateInstance(typeof(ValueTupleFieldsConverter<>).MakeGenericType(typeToConvert))!; } private sealed class ValueTupleFieldsConverter : JsonConverter { private static readonly FieldInfo[] Fields = typeof(T).GetFields(); public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WriteStartObject(); foreach (var field in Fields) { writer.WritePropertyName(field.Name); var fieldValue = field.GetValue(value); if (fieldValue == null) writer.WriteNullValue(); else JsonSerializer.Serialize(writer, fieldValue, fieldValue.GetType(), options); } writer.WriteEndObject(); } public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object) throw new JsonException($"A {typeof(T)} key part must be a JSON object, got {root.ValueKind}."); var args = new object?[Fields.Length]; for (int i = 0; i < Fields.Length; i++) { if (root.TryGetProperty(Fields[i].Name, out var element)) args[i] = element.Deserialize(Fields[i].FieldType, options); } return (T)Activator.CreateInstance(typeof(T), args)!; } } /// /// Deserialize _array_index text value to key /// /// Type of key /// String from _array_index column /// Deserialized key public static TKey Deserialize(string arrayIndex) { if (arrayIndex == null) throw new ArgumentNullException(nameof(arrayIndex), "_array_index cannot be null for Dictionary element"); return (TKey)DeserializeObject(arrayIndex, typeof(TKey))!; } /// /// Deserialize _array_index text value to key (non-generic version) /// /// String from _array_index column /// Type of key /// Deserialized key public static object? DeserializeObject(string arrayIndex, Type keyType) { if (arrayIndex == null) throw new ArgumentNullException(nameof(arrayIndex), "_array_index cannot be null for Dictionary element"); // String types if (keyType == typeof(string)) return arrayIndex; if (keyType == typeof(char)) return arrayIndex.Length > 0 ? arrayIndex[0] : '\0'; // Integer types if (keyType == typeof(long)) return long.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(int)) return int.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(short)) return short.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(byte)) return byte.Parse(arrayIndex, CultureInfo.InvariantCulture); // Floating point if (keyType == typeof(double)) return double.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(float)) return float.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(decimal)) return decimal.Parse(arrayIndex, CultureInfo.InvariantCulture); // Boolean if (keyType == typeof(bool)) return arrayIndex.Equals("true", StringComparison.OrdinalIgnoreCase); // DateTime types if (keyType == typeof(DateTime)) return DateTime.Parse(arrayIndex, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); if (keyType == typeof(DateTimeOffset)) return DateTimeOffset.Parse(arrayIndex, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); if (keyType == typeof(DateOnly)) return DateOnly.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(TimeOnly)) return TimeOnly.Parse(arrayIndex, CultureInfo.InvariantCulture); if (keyType == typeof(TimeSpan)) return TimeSpan.Parse(arrayIndex, CultureInfo.InvariantCulture); // Guid if (keyType == typeof(Guid)) return Guid.Parse(arrayIndex); // Byte array - Base64 if (keyType == typeof(byte[])) return Convert.FromBase64String(arrayIndex); // Enum if (keyType.IsEnum) return Enum.Parse(keyType, arrayIndex); // Complex keys (Tuple, custom classes) - Base64-encoded JSON var json = Encoding.UTF8.GetString(Convert.FromBase64String(arrayIndex)); return JsonSerializer.Deserialize(json, keyType, KeyJsonOptions); } /// /// Check if key type is a complex type requiring JSON serialization /// /// Type to check /// True if type requires JSON serialization public static bool IsComplexKey(Type keyType) { // Simple types that don't need JSON if (keyType == typeof(string) || keyType == typeof(char)) return false; if (keyType == typeof(long) || keyType == typeof(int) || keyType == typeof(short) || keyType == typeof(byte)) return false; if (keyType == typeof(double) || keyType == typeof(float) || keyType == typeof(decimal)) return false; if (keyType == typeof(bool)) return false; if (keyType == typeof(DateTime) || keyType == typeof(DateTimeOffset) || keyType == typeof(DateOnly) || keyType == typeof(TimeOnly) || keyType == typeof(TimeSpan)) return false; if (keyType == typeof(Guid)) return false; if (keyType == typeof(byte[])) return false; if (keyType.IsEnum) return false; // Everything else is complex (Tuple, ValueTuple, custom classes, etc.) return true; } /// /// Get RedbTypeIds constant for key type /// /// C# key type /// Type ID for _structures._key_type column public static long GetKeyTypeId(Type keyType) { if (keyType == typeof(string)) return RedbTypeIds.String; if (keyType == typeof(char)) return RedbTypeIds.Char; if (keyType == typeof(long)) return RedbTypeIds.Long; if (keyType == typeof(int)) return RedbTypeIds.Int; if (keyType == typeof(short)) return RedbTypeIds.Short; if (keyType == typeof(byte)) return RedbTypeIds.Byte; if (keyType == typeof(double)) return RedbTypeIds.Double; if (keyType == typeof(float)) return RedbTypeIds.Float; if (keyType == typeof(decimal)) return RedbTypeIds.Decimal; if (keyType == typeof(bool)) return RedbTypeIds.Boolean; if (keyType == typeof(DateTime)) return RedbTypeIds.DateTime; if (keyType == typeof(DateTimeOffset)) return RedbTypeIds.DateTimeOffset; if (keyType == typeof(DateOnly)) return RedbTypeIds.DateOnly; if (keyType == typeof(TimeOnly)) return RedbTypeIds.TimeOnly; if (keyType == typeof(TimeSpan)) return RedbTypeIds.TimeSpan; if (keyType == typeof(Guid)) return RedbTypeIds.Guid; if (keyType == typeof(byte[])) return RedbTypeIds.ByteArray; if (keyType.IsEnum) return RedbTypeIds.Enum; // Complex keys (Tuple, custom classes) stored as Base64-encoded JSON // Using Class type to distinguish from simple String keys return RedbTypeIds.Class; } /// /// Check if C# type is valid as Dictionary key /// /// Type to check /// True if type can be used as Dictionary key public static bool CanBeKey(Type keyType) { // All serializable types can be keys // Only excluded: types that can't be serialized deterministically if (keyType == typeof(object)) return false; // Dynamic types are not supported if (keyType.FullName == "System.Object") return false; return true; } }