DictionaryAdapter
DictionaryAdapter type-casts dictionary TKey and TValue types.
// Byte map
IDictionary<ulong, byte[]> files = new Dictionary<ulong, byte[]>();
// Files based car serializer
IDictionary<string, Car> cars = new DictionaryAdapter<ulong, byte[], string, Car>(
files, null, id => new FNVHash64().HashIn(id), Car.Deserialize, c => c.Serialize(), null, c => c.Id
);
// Write car
cars["XYZ-123"] = new Car { Id = "XYZ-123", Name = "My Car" };
// Read car
Car car = cars["XYZ-123"];
// List cars
foreach (Car _car in cars.Values)
Console.WriteLine(_car);
public record Car
{
static UTF8Encoding encoding = new UTF8Encoding(false);
public string Id { get; set; } = "id";
public string Name { get; set; } = "";
public static Car Deserialize(byte[] data)
{
// Read id
int len = data[0];
string id = encoding.GetString(data, 1, len);
// Read string
string name = encoding.GetString(data, len + 1, data.Length - len - 1);
//
return new Car { Id = id, Name = name };
}
public byte[] Serialize()
{
MemoryStream ms = new MemoryStream();
// Write Id
byte[] idBytes = encoding.GetBytes(Id);
ms.WriteByte((byte)idBytes.Length);
for (int i = 0; i < idBytes.Length; i++) ms.WriteByte(idBytes[i]);
// Write name
byte[] nameBytes = encoding.GetBytes(Name);
for (int i = 0; i < nameBytes.Length; i++) ms.WriteByte(nameBytes[i]);
ms.Flush();
return ms.ToArray();
}
}
See FileDictionary for more.
Full Example
Full example
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Avalanche.Utilities;
using static System.Console;
public class dictionaryadapter
{
public static void Run()
{
{
// <01>
// Byte map
IDictionary<ulong, byte[]> files = new Dictionary<ulong, byte[]>();
// Files based car serializer
IDictionary<string, Car> cars = new DictionaryAdapter<ulong, byte[], string, Car>(
files, null, id => new FNVHash64().HashIn(id), Car.Deserialize, c => c.Serialize(), null, c => c.Id
);
// Write car
cars["XYZ-123"] = new Car { Id = "XYZ-123", Name = "My Car" };
// Read car
Car car = cars["XYZ-123"];
// List cars
foreach (Car _car in cars.Values)
Console.WriteLine(_car);
// </01>
}
}
// <05>
public record Car
{
static UTF8Encoding encoding = new UTF8Encoding(false);
public string Id { get; set; } = "id";
public string Name { get; set; } = "";
public static Car Deserialize(byte[] data)
{
// Read id
int len = data[0];
string id = encoding.GetString(data, 1, len);
// Read string
string name = encoding.GetString(data, len + 1, data.Length - len - 1);
//
return new Car { Id = id, Name = name };
}
public byte[] Serialize()
{
MemoryStream ms = new MemoryStream();
// Write Id
byte[] idBytes = encoding.GetBytes(Id);
ms.WriteByte((byte)idBytes.Length);
for (int i = 0; i < idBytes.Length; i++) ms.WriteByte(idBytes[i]);
// Write name
byte[] nameBytes = encoding.GetBytes(Name);
for (int i = 0; i < nameBytes.Length; i++) ms.WriteByte(nameBytes[i]);
ms.Flush();
return ms.ToArray();
}
}
// </05>
}