Initial version
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\EonaCat.FastBin\EonaCat.FastBin.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
260
EonaCat.FastBin.Tester.Client/Program.cs
Normal file
260
EonaCat.FastBin.Tester.Client/Program.cs
Normal file
@@ -0,0 +1,260 @@
|
||||
namespace EonaCat.FastBin.Tester
|
||||
{
|
||||
public class User
|
||||
{
|
||||
public int Id;
|
||||
public string Name;
|
||||
public string Email;
|
||||
public DateTime CreatedAt;
|
||||
public List<Order> Orders;
|
||||
public User Manager; // Self-referencing for testing
|
||||
}
|
||||
|
||||
public class Order
|
||||
{
|
||||
public Guid OrderId;
|
||||
public decimal TotalAmount;
|
||||
public List<OrderItem> Items;
|
||||
public OrderStatus Status;
|
||||
}
|
||||
|
||||
public class OrderItem
|
||||
{
|
||||
public string ProductName;
|
||||
public int Quantity;
|
||||
public decimal Price;
|
||||
}
|
||||
|
||||
public enum OrderStatus
|
||||
{
|
||||
Pending,
|
||||
Processing,
|
||||
Shipped,
|
||||
Delivered
|
||||
}
|
||||
|
||||
public class GetUserRequest
|
||||
{
|
||||
public int UserId;
|
||||
}
|
||||
|
||||
public class CreateOrderRequest
|
||||
{
|
||||
public int UserId;
|
||||
public List<OrderItem> Items;
|
||||
}
|
||||
|
||||
public class CreateOrderResponse
|
||||
{
|
||||
public Guid OrderId;
|
||||
public string Message;
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
Console.WriteLine("=== EonaCat.FastBin Tester ===\n");
|
||||
|
||||
// Test 1: Basic Serialization
|
||||
Console.WriteLine("Test 1: Basic Serialization");
|
||||
TestBasicSerialization();
|
||||
|
||||
// Test 2: Complex Objects with Nesting
|
||||
Console.WriteLine("\nTest 2: Complex Objects with Nesting");
|
||||
TestComplexObjects();
|
||||
|
||||
// Test 3: Self-Referencing Objects
|
||||
Console.WriteLine("\nTest 3: Self-Referencing Objects");
|
||||
TestSelfReferencing();
|
||||
|
||||
// Test 4: Polymorphism
|
||||
Console.WriteLine("\nTest 4: Polymorphism");
|
||||
TestPolymorphism();
|
||||
|
||||
// Test 5: Client-Server Communication
|
||||
Console.WriteLine("\nTest 5: Client-Server Communication");
|
||||
await TestClientServer();
|
||||
|
||||
Console.WriteLine("\n=== All EonaCat.FastBin Tests Complete ===");
|
||||
Console.WriteLine("Press any key to exit...");
|
||||
Console.ReadKey();
|
||||
}
|
||||
|
||||
static void TestBasicSerialization()
|
||||
{
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
["string"] = "Someone is a brasser",
|
||||
["int"] = 42,
|
||||
["double"] = 3.14159,
|
||||
["bool"] = true,
|
||||
["guid"] = Guid.NewGuid(),
|
||||
["date"] = DateTime.Now
|
||||
};
|
||||
|
||||
var bytes = FastBin.Serialize(data);
|
||||
var restored = FastBin.Deserialize<Dictionary<string, object>>(bytes);
|
||||
|
||||
Console.WriteLine($"Original count: {data.Count}");
|
||||
Console.WriteLine($"Restored count: {restored.Count}");
|
||||
Console.WriteLine($"Serialized size: {bytes.Length} bytes");
|
||||
Console.WriteLine("Basic serialization works!");
|
||||
}
|
||||
|
||||
static void TestComplexObjects()
|
||||
{
|
||||
var user = new User
|
||||
{
|
||||
Id = 1,
|
||||
Name = "Brian Asser",
|
||||
Email = "brasser@example.com",
|
||||
CreatedAt = DateTime.Now,
|
||||
Orders = new List<Order>
|
||||
{
|
||||
new Order
|
||||
{
|
||||
OrderId = Guid.NewGuid(),
|
||||
TotalAmount = 299.99m,
|
||||
Status = OrderStatus.Delivered,
|
||||
Items = new List<OrderItem>
|
||||
{
|
||||
new OrderItem { ProductName = "Laptop", Quantity = 1, Price = 299.99m }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var bytes = FastBin.Serialize(user);
|
||||
var restored = FastBin.Deserialize<User>(bytes);
|
||||
|
||||
Console.WriteLine($"User: {restored.Name}");
|
||||
Console.WriteLine($"Orders: {restored.Orders.Count}");
|
||||
Console.WriteLine($"First order total: ${restored.Orders[0].TotalAmount}");
|
||||
Console.WriteLine($"Serialized size: {bytes.Length} bytes");
|
||||
Console.WriteLine("Complex objects work!");
|
||||
}
|
||||
|
||||
static void TestSelfReferencing()
|
||||
{
|
||||
var manager = new User
|
||||
{
|
||||
Id = 1,
|
||||
Name = "Manager",
|
||||
Email = "manager@example.com",
|
||||
CreatedAt = DateTime.Now
|
||||
};
|
||||
|
||||
var employee = new User
|
||||
{
|
||||
Id = 2,
|
||||
Name = "Brasser",
|
||||
Email = "brasser@example.com",
|
||||
CreatedAt = DateTime.Now,
|
||||
Manager = manager
|
||||
};
|
||||
|
||||
manager.Manager = manager; // Self-reference
|
||||
|
||||
var bytes = FastBin.Serialize(employee);
|
||||
var restored = FastBin.Deserialize<User>(bytes);
|
||||
|
||||
Console.WriteLine($"Employee: {restored.Name}");
|
||||
Console.WriteLine($"Manager: {restored.Manager.Name}");
|
||||
Console.WriteLine($"Manager's manager: {restored.Manager.Manager.Name}");
|
||||
Console.WriteLine($"Self-reference intact: {ReferenceEquals(restored.Manager, restored.Manager.Manager)}");
|
||||
Console.WriteLine("Self-referencing works!");
|
||||
}
|
||||
|
||||
static void TestPolymorphism()
|
||||
{
|
||||
object[] items = new object[]
|
||||
{
|
||||
"A string",
|
||||
42,
|
||||
new User { Id = 1, Name = "ThisGuy", Email = "ThisGuy@test.com", CreatedAt = DateTime.Now },
|
||||
new Order { OrderId = Guid.NewGuid(), TotalAmount = 99.99m, Status = OrderStatus.Pending }
|
||||
};
|
||||
|
||||
var bytes = FastBin.Serialize(items);
|
||||
var restored = FastBin.Deserialize<object[]>(bytes);
|
||||
|
||||
Console.WriteLine($"Item 0: {restored[0]} (type: {restored[0].GetType().Name})");
|
||||
Console.WriteLine($"Item 1: {restored[1]} (type: {restored[1].GetType().Name})");
|
||||
Console.WriteLine($"Item 2: {((User)restored[2]).Name} (type: {restored[2].GetType().Name})");
|
||||
Console.WriteLine($"Item 3: ${((Order)restored[3]).TotalAmount} (type: {restored[3].GetType().Name})");
|
||||
Console.WriteLine("Polymorphism works!");
|
||||
}
|
||||
|
||||
static async Task TestClientServer()
|
||||
{
|
||||
var server = new FastServer();
|
||||
|
||||
// Register handlers
|
||||
server.RegisterHandler<GetUserRequest, User>("GetUser", request =>
|
||||
{
|
||||
return new User
|
||||
{
|
||||
Id = request.UserId,
|
||||
Name = "Brian Asser",
|
||||
Email = "Brasser@example.com",
|
||||
CreatedAt = DateTime.Now,
|
||||
Orders = new List<Order>()
|
||||
};
|
||||
});
|
||||
|
||||
server.RegisterHandler<CreateOrderRequest, CreateOrderResponse>("CreateOrder", request =>
|
||||
{
|
||||
return new CreateOrderResponse
|
||||
{
|
||||
OrderId = Guid.NewGuid(),
|
||||
Message = $"Order created for user {request.UserId} with {request.Items.Count} items"
|
||||
};
|
||||
});
|
||||
|
||||
// Start server in background
|
||||
var serverTask = Task.Run(() => server.StartAsync(5000));
|
||||
|
||||
// Give server time to start
|
||||
await Task.Delay(1000);
|
||||
|
||||
try
|
||||
{
|
||||
// Create client
|
||||
using (var client = new FastClient())
|
||||
{
|
||||
await client.ConnectAsync("localhost", 5000);
|
||||
Console.WriteLine("Connected to server");
|
||||
|
||||
// Test GetUser
|
||||
var user = await client.CallAsync<GetUserRequest, User>(
|
||||
"GetUser",
|
||||
new GetUserRequest { UserId = 123 }
|
||||
);
|
||||
Console.WriteLine($"Retrieved user: {user.Name} ({user.Email})");
|
||||
|
||||
// Test CreateOrder
|
||||
var orderResponse = await client.CallAsync<CreateOrderRequest, CreateOrderResponse>(
|
||||
"CreateOrder",
|
||||
new CreateOrderRequest
|
||||
{
|
||||
UserId = 123,
|
||||
Items = new List<OrderItem>
|
||||
{
|
||||
new OrderItem { ProductName = "Widget", Quantity = 5, Price = 19.99m }
|
||||
}
|
||||
}
|
||||
);
|
||||
Console.WriteLine($"Created order: {orderResponse.OrderId}");
|
||||
Console.WriteLine($"Message: {orderResponse.Message}");
|
||||
}
|
||||
|
||||
Console.WriteLine("Client-Server communication works!");
|
||||
}
|
||||
finally
|
||||
{
|
||||
server.Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
70
EonaCat.FastBin.sln
Normal file
70
EonaCat.FastBin.sln
Normal file
@@ -0,0 +1,70 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.14.36603.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.FastBin", "EonaCat.FastBin\EonaCat.FastBin.csproj", "{F737B8B4-625D-486F-BE46-9322E0FCA6F2}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.FastBin.Tester.Client", "EonaCat.FastBin.Tester.Client\EonaCat.FastBin.Tester.Client.csproj", "{0609E3F6-9E06-4029-840F-4836067A3273}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Benchmarks", "Benchmarks", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.FastBin.Benchmarks", "EonaCat.FastBin.Benchmarks\EonaCat.FastBin.Benchmarks.csproj", "{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Release|x64.Build.0 = Release|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{F737B8B4-625D-486F-BE46-9322E0FCA6F2}.Release|x86.Build.0 = Release|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Release|x64.Build.0 = Release|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{0609E3F6-9E06-4029-840F-4836067A3273}.Release|x86.Build.0 = Release|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{E9D44250-1A2F-48A8-95D6-7F87A8755FC5} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {4656DE77-1FB9-4D0B-B464-D8E54334C463}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
22
EonaCat.FastBin/DeserializationContext.cs
Normal file
22
EonaCat.FastBin/DeserializationContext.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
internal class DeserializationContext
|
||||
{
|
||||
private readonly Dictionary<int, object> _objectReferences = new Dictionary<int, object>();
|
||||
|
||||
public void RegisterObject(int id, object obj)
|
||||
{
|
||||
_objectReferences[id] = obj;
|
||||
}
|
||||
|
||||
public object GetObject(int id)
|
||||
{
|
||||
_objectReferences.TryGetValue(id, out var obj);
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
EonaCat.FastBin/EonaCat.FastBin.csproj
Normal file
39
EonaCat.FastBin/EonaCat.FastBin.csproj
Normal file
@@ -0,0 +1,39 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<PackageId>EonaCat.FastBin</PackageId>
|
||||
<Title>EonaCat.FastBin</Title>
|
||||
<Version>1.0.0</Version>
|
||||
<Authors>EonaCat (Jeroen Saey)</Authors>
|
||||
<Company>EonaCat (Jeroen Saey)</Company>
|
||||
<Description>With EonaCat.FastBin you can serialize and deserialize fast and efficiently.</Description>
|
||||
<Copyright>EonaCat (Jeroen Saey)</Copyright>
|
||||
<PackageProjectUrl>https://git.saey.me/EonaCat/EonaCat.FastBin</PackageProjectUrl>
|
||||
<PackageIcon>icon.png</PackageIcon>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.FastBin</RepositoryUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<PackageTags>Fast, Server, Client, Jeroen, Saey, Json, MessagePack, Performance</PackageTags>
|
||||
<PackageReleaseNotes>With EonaCat.FastBin you can serialize and deserialize fast and efficiently.</PackageReleaseNotes>
|
||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="..\icon.png">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
<None Include="..\LICENSE">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
<None Include="..\README.md">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
80
EonaCat.FastBin/FastBin.cs
Normal file
80
EonaCat.FastBin/FastBin.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
public static class FastBin
|
||||
{
|
||||
private static readonly Dictionary<Type, int> _typeCache = new Dictionary<Type, int>();
|
||||
private static readonly Dictionary<int, Type> _reverseTypeCache = new Dictionary<int, Type>();
|
||||
private static readonly Dictionary<Type, FieldInfo[]> _fieldCache = new Dictionary<Type, FieldInfo[]>();
|
||||
private static int _typeIdCounter = 0;
|
||||
private static readonly object _lock = new object();
|
||||
|
||||
public static byte[] Serialize<T>(T obj)
|
||||
{
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
using (var writer = new FastWriter(stream))
|
||||
{
|
||||
var context = new SerializationContext();
|
||||
writer.WriteObject(obj, typeof(T), context);
|
||||
}
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static T Deserialize<T>(byte[] data)
|
||||
{
|
||||
using (var stream = new MemoryStream(data))
|
||||
using (var reader = new FastReader(stream))
|
||||
{
|
||||
var context = new DeserializationContext();
|
||||
return (T)reader.ReadObject(typeof(T), context);
|
||||
}
|
||||
}
|
||||
|
||||
internal static int GetTypeId(Type type)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_typeCache.TryGetValue(type, out int id))
|
||||
{
|
||||
id = ++_typeIdCounter;
|
||||
_typeCache[type] = id;
|
||||
_reverseTypeCache[id] = type;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
internal static Type GetTypeById(int id)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_reverseTypeCache.TryGetValue(id, out var type);
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
internal static FieldInfo[] GetFields(Type type)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_fieldCache.TryGetValue(type, out var fields))
|
||||
{
|
||||
fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
|
||||
.OrderBy(f => f.Name)
|
||||
.ToArray();
|
||||
_fieldCache[type] = fields;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
71
EonaCat.FastBin/FastClient.cs
Normal file
71
EonaCat.FastBin/FastClient.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
public class FastClient : IDisposable
|
||||
{
|
||||
private TcpClient _client;
|
||||
private NetworkStream _stream;
|
||||
|
||||
public async Task ConnectAsync(string host, int port)
|
||||
{
|
||||
_client = new TcpClient();
|
||||
await _client.ConnectAsync(host, port);
|
||||
_stream = _client.GetStream();
|
||||
}
|
||||
|
||||
public async Task<TResponse> CallAsync<TRequest, TResponse>(string route, TRequest data)
|
||||
{
|
||||
var request = new FastRequest
|
||||
{
|
||||
Route = route,
|
||||
Data = data
|
||||
};
|
||||
|
||||
byte[] requestBytes = FastBin.Serialize(request);
|
||||
byte[] lengthBytes = BitConverter.GetBytes(requestBytes.Length);
|
||||
|
||||
await _stream.WriteAsync(lengthBytes, 0, 4);
|
||||
await _stream.WriteAsync(requestBytes, 0, requestBytes.Length);
|
||||
|
||||
// Read response length
|
||||
byte[] responseLengthBytes = new byte[4];
|
||||
await _stream.ReadAsync(responseLengthBytes, 0, 4);
|
||||
int responseLength = BitConverter.ToInt32(responseLengthBytes, 0);
|
||||
|
||||
// Read response
|
||||
byte[] responseBytes = new byte[responseLength];
|
||||
int totalRead = 0;
|
||||
while (totalRead < responseLength)
|
||||
{
|
||||
int read = await _stream.ReadAsync(responseBytes, totalRead, responseLength - totalRead);
|
||||
if (read == 0)
|
||||
{
|
||||
throw new IOException("Connection closed");
|
||||
}
|
||||
|
||||
totalRead += read;
|
||||
}
|
||||
|
||||
var response = FastBin.Deserialize<FastResponse>(responseBytes);
|
||||
|
||||
if (!response.Success)
|
||||
{
|
||||
throw new Exception(response.Error);
|
||||
}
|
||||
|
||||
return (TResponse)response.Data;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stream?.Dispose();
|
||||
_client?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
201
EonaCat.FastBin/FastReader.cs
Normal file
201
EonaCat.FastBin/FastReader.cs
Normal file
@@ -0,0 +1,201 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
internal class FastReader : IDisposable
|
||||
{
|
||||
private readonly BinaryReader _reader;
|
||||
|
||||
public FastReader(Stream stream)
|
||||
{
|
||||
_reader = new BinaryReader(stream, Encoding.UTF8, true);
|
||||
}
|
||||
|
||||
public object ReadObject(Type expectedType, DeserializationContext context)
|
||||
{
|
||||
byte marker = _reader.ReadByte();
|
||||
|
||||
if (marker == (byte)TypeCode.Empty)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Reference
|
||||
if (marker == Markers.Reference)
|
||||
{
|
||||
int refId = Read7BitEncodedInt();
|
||||
return context.GetObject(refId);
|
||||
}
|
||||
|
||||
// Guid
|
||||
if (marker == Markers.Guid)
|
||||
{
|
||||
return new Guid(_reader.ReadBytes(16));
|
||||
}
|
||||
|
||||
// Array
|
||||
if (marker == Markers.Array)
|
||||
{
|
||||
return ReadArray(context);
|
||||
}
|
||||
|
||||
// List
|
||||
if (marker == Markers.List)
|
||||
{
|
||||
return ReadList(context);
|
||||
}
|
||||
|
||||
// Dictionary
|
||||
if (marker == Markers.Dictionary)
|
||||
{
|
||||
return ReadDictionary(context);
|
||||
}
|
||||
|
||||
// Complex object
|
||||
if (marker == Markers.ComplexObject)
|
||||
{
|
||||
return ReadComplexObject(expectedType, context);
|
||||
}
|
||||
|
||||
// Primitive
|
||||
return ReadPrimitive((TypeCode)marker);
|
||||
}
|
||||
|
||||
private object ReadPrimitive(TypeCode typeCode)
|
||||
{
|
||||
switch (typeCode)
|
||||
{
|
||||
case TypeCode.Boolean: return _reader.ReadBoolean();
|
||||
case TypeCode.Byte: return _reader.ReadByte();
|
||||
case TypeCode.SByte: return _reader.ReadSByte();
|
||||
case TypeCode.Int16: return _reader.ReadInt16();
|
||||
case TypeCode.UInt16: return _reader.ReadUInt16();
|
||||
case TypeCode.Int32: return _reader.ReadInt32();
|
||||
case TypeCode.UInt32: return _reader.ReadUInt32();
|
||||
case TypeCode.Int64: return _reader.ReadInt64();
|
||||
case TypeCode.UInt64: return _reader.ReadUInt64();
|
||||
case TypeCode.Single: return _reader.ReadSingle();
|
||||
case TypeCode.Double: return _reader.ReadDouble();
|
||||
case TypeCode.Decimal: return _reader.ReadDecimal();
|
||||
case TypeCode.String: return _reader.ReadString();
|
||||
case TypeCode.DateTime: return DateTime.FromBinary(_reader.ReadInt64());
|
||||
default: throw new InvalidDataException($"Unknown type code: {typeCode}");
|
||||
}
|
||||
}
|
||||
|
||||
private Array ReadArray(DeserializationContext context)
|
||||
{
|
||||
int objId = Read7BitEncodedInt();
|
||||
int elementTypeId = Read7BitEncodedInt();
|
||||
int length = Read7BitEncodedInt();
|
||||
|
||||
Type elementType = FastBin.GetTypeById(elementTypeId);
|
||||
Array array = Array.CreateInstance(elementType, length);
|
||||
context.RegisterObject(objId, array);
|
||||
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
array.SetValue(ReadObject(elementType, context), i);
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
private IList ReadList(DeserializationContext context)
|
||||
{
|
||||
int objId = Read7BitEncodedInt();
|
||||
int elementTypeId = Read7BitEncodedInt();
|
||||
int count = Read7BitEncodedInt();
|
||||
|
||||
Type elementType = FastBin.GetTypeById(elementTypeId);
|
||||
Type listType = typeof(List<>).MakeGenericType(elementType);
|
||||
IList list = (IList)Activator.CreateInstance(listType);
|
||||
context.RegisterObject(objId, list);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
list.Add(ReadObject(elementType, context));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private IDictionary ReadDictionary(DeserializationContext context)
|
||||
{
|
||||
int objId = Read7BitEncodedInt();
|
||||
int keyTypeId = Read7BitEncodedInt();
|
||||
int valueTypeId = Read7BitEncodedInt();
|
||||
int count = Read7BitEncodedInt();
|
||||
|
||||
Type keyType = FastBin.GetTypeById(keyTypeId);
|
||||
Type valueType = FastBin.GetTypeById(valueTypeId);
|
||||
Type dictType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
|
||||
IDictionary dict = (IDictionary)Activator.CreateInstance(dictType);
|
||||
context.RegisterObject(objId, dict);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var key = ReadObject(keyType, context);
|
||||
var value = ReadObject(valueType, context);
|
||||
dict.Add(key, value);
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
private object ReadComplexObject(Type expectedType, DeserializationContext context)
|
||||
{
|
||||
int objId = Read7BitEncodedInt();
|
||||
bool isPolymorphic = _reader.ReadBoolean();
|
||||
|
||||
Type actualType = expectedType;
|
||||
if (isPolymorphic)
|
||||
{
|
||||
int typeId = Read7BitEncodedInt();
|
||||
actualType = FastBin.GetTypeById(typeId);
|
||||
}
|
||||
|
||||
object obj = FormatterServices.GetUninitializedObject(actualType);
|
||||
context.RegisterObject(objId, obj);
|
||||
|
||||
int fieldCount = Read7BitEncodedInt();
|
||||
var fields = FastBin.GetFields(actualType);
|
||||
|
||||
for (int i = 0; i < fieldCount; i++)
|
||||
{
|
||||
var value = ReadObject(fields[i].FieldType, context);
|
||||
fields[i].SetValue(obj, value);
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
private int Read7BitEncodedInt()
|
||||
{
|
||||
int result = 0;
|
||||
int shift = 0;
|
||||
byte b;
|
||||
|
||||
do
|
||||
{
|
||||
b = _reader.ReadByte();
|
||||
result |= (b & 0x7F) << shift;
|
||||
shift += 7;
|
||||
} while ((b & 0x80) != 0);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_reader?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
10
EonaCat.FastBin/FastRequest.cs
Normal file
10
EonaCat.FastBin/FastRequest.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
internal class FastRequest
|
||||
{
|
||||
public string Route;
|
||||
public object Data;
|
||||
}
|
||||
}
|
||||
11
EonaCat.FastBin/FastResponse.cs
Normal file
11
EonaCat.FastBin/FastResponse.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
internal class FastResponse
|
||||
{
|
||||
public bool Success;
|
||||
public object Data;
|
||||
public string Error;
|
||||
}
|
||||
}
|
||||
131
EonaCat.FastBin/FastServer.cs
Normal file
131
EonaCat.FastBin/FastServer.cs
Normal file
@@ -0,0 +1,131 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
public class FastServer
|
||||
{
|
||||
private TcpListener _listener;
|
||||
private readonly Dictionary<string, Func<object, Task<object>>> _handlers = new Dictionary<string, Func<object, Task<object>>>();
|
||||
private bool _running;
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
|
||||
public void RegisterHandler<TRequest, TResponse>(string route, Func<TRequest, Task<TResponse>> handler)
|
||||
{
|
||||
_handlers[route] = async (obj) => await handler((TRequest)obj);
|
||||
}
|
||||
|
||||
public void RegisterHandler<TRequest, TResponse>(string route, Func<TRequest, TResponse> handler)
|
||||
{
|
||||
_handlers[route] = (obj) => Task.FromResult<object>(handler((TRequest)obj));
|
||||
}
|
||||
|
||||
public async Task StartAsync(int port)
|
||||
{
|
||||
_listener = new TcpListener(IPAddress.Any, port);
|
||||
_listener.Start();
|
||||
_running = true;
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
Console.WriteLine($"FastServer listening on port {port}");
|
||||
|
||||
while (_running)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync();
|
||||
#pragma warning disable CS4014
|
||||
Task.Run(() => HandleClientAsync(client));
|
||||
#pragma warning restore CS4014
|
||||
}
|
||||
catch (Exception ex) when (_running)
|
||||
{
|
||||
Console.WriteLine($"EonaCat.FastBin: Error accepting client: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleClientAsync(TcpClient client)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (client)
|
||||
using (var stream = client.GetStream())
|
||||
{
|
||||
while (client.Connected && _running)
|
||||
{
|
||||
// Read message length
|
||||
byte[] lengthBytes = new byte[4];
|
||||
int read = await stream.ReadAsync(lengthBytes, 0, 4);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
int length = BitConverter.ToInt32(lengthBytes, 0);
|
||||
|
||||
// Read message
|
||||
byte[] messageBytes = new byte[length];
|
||||
int totalRead = 0;
|
||||
while (totalRead < length)
|
||||
{
|
||||
read = await stream.ReadAsync(messageBytes, totalRead, length - totalRead);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
totalRead += read;
|
||||
}
|
||||
|
||||
// Deserialize request
|
||||
var request = FastBin.Deserialize<FastRequest>(messageBytes);
|
||||
|
||||
// Process
|
||||
FastResponse response;
|
||||
if (_handlers.TryGetValue(request.Route, out var handler))
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await handler(request.Data);
|
||||
response = new FastResponse { Success = true, Data = result };
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
response = new FastResponse { Success = false, Error = ex.Message };
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
response = new FastResponse { Success = false, Error = "Route not found" };
|
||||
}
|
||||
|
||||
// Serialize and send response
|
||||
byte[] responseBytes = FastBin.Serialize(response);
|
||||
byte[] responseLengthBytes = BitConverter.GetBytes(responseBytes.Length);
|
||||
|
||||
await stream.WriteAsync(responseLengthBytes, 0, 4);
|
||||
await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Client error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_running = false;
|
||||
_cancellationTokenSource?.Cancel();
|
||||
_listener?.Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
249
EonaCat.FastBin/FastWriter.cs
Normal file
249
EonaCat.FastBin/FastWriter.cs
Normal file
@@ -0,0 +1,249 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
internal class FastWriter : IDisposable
|
||||
{
|
||||
private readonly BinaryWriter _writer;
|
||||
|
||||
public FastWriter(Stream stream)
|
||||
{
|
||||
_writer = new BinaryWriter(stream, Encoding.UTF8, true);
|
||||
}
|
||||
|
||||
public void WriteObject(object obj, Type declaredType, SerializationContext context)
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
_writer.Write((byte)TypeCode.Empty);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for circular reference
|
||||
if (context.TryGetObjectId(obj, out int refId))
|
||||
{
|
||||
// Reference marker
|
||||
_writer.Write(Markers.Reference);
|
||||
Write7BitEncodedInt(refId);
|
||||
return;
|
||||
}
|
||||
|
||||
Type actualType = obj.GetType();
|
||||
|
||||
// Handle primitives and special types
|
||||
if (TryWritePrimitive(obj, actualType))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (actualType.IsArray)
|
||||
{
|
||||
WriteArray((Array)obj, context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (obj is IList list)
|
||||
{
|
||||
WriteList(list, actualType, context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (obj is IDictionary dict)
|
||||
{
|
||||
WriteDictionary(dict, actualType, context);
|
||||
return;
|
||||
}
|
||||
|
||||
// Complex object
|
||||
WriteComplexObject(obj, actualType, declaredType, context);
|
||||
}
|
||||
|
||||
private bool TryWritePrimitive(object obj, Type type)
|
||||
{
|
||||
var typeCode = Type.GetTypeCode(type);
|
||||
|
||||
switch (typeCode)
|
||||
{
|
||||
case TypeCode.Boolean:
|
||||
_writer.Write((byte)TypeCode.Boolean);
|
||||
_writer.Write((bool)obj);
|
||||
return true;
|
||||
case TypeCode.Byte:
|
||||
_writer.Write((byte)TypeCode.Byte);
|
||||
_writer.Write((byte)obj);
|
||||
return true;
|
||||
case TypeCode.SByte:
|
||||
_writer.Write((byte)TypeCode.SByte);
|
||||
_writer.Write((sbyte)obj);
|
||||
return true;
|
||||
case TypeCode.Int16:
|
||||
_writer.Write((byte)TypeCode.Int16);
|
||||
_writer.Write((short)obj);
|
||||
return true;
|
||||
case TypeCode.UInt16:
|
||||
_writer.Write((byte)TypeCode.UInt16);
|
||||
_writer.Write((ushort)obj);
|
||||
return true;
|
||||
case TypeCode.Int32:
|
||||
_writer.Write((byte)TypeCode.Int32);
|
||||
_writer.Write((int)obj);
|
||||
return true;
|
||||
case TypeCode.UInt32:
|
||||
_writer.Write((byte)TypeCode.UInt32);
|
||||
_writer.Write((uint)obj);
|
||||
return true;
|
||||
case TypeCode.Int64:
|
||||
_writer.Write((byte)TypeCode.Int64);
|
||||
_writer.Write((long)obj);
|
||||
return true;
|
||||
case TypeCode.UInt64:
|
||||
_writer.Write((byte)TypeCode.UInt64);
|
||||
_writer.Write((ulong)obj);
|
||||
return true;
|
||||
case TypeCode.Single:
|
||||
_writer.Write((byte)TypeCode.Single);
|
||||
_writer.Write((float)obj);
|
||||
return true;
|
||||
case TypeCode.Double:
|
||||
_writer.Write((byte)TypeCode.Double);
|
||||
_writer.Write((double)obj);
|
||||
return true;
|
||||
case TypeCode.Decimal:
|
||||
_writer.Write((byte)TypeCode.Decimal);
|
||||
_writer.Write((decimal)obj);
|
||||
return true;
|
||||
case TypeCode.String:
|
||||
_writer.Write((byte)TypeCode.String);
|
||||
_writer.Write((string)obj);
|
||||
return true;
|
||||
case TypeCode.DateTime:
|
||||
_writer.Write((byte)TypeCode.DateTime);
|
||||
_writer.Write(((DateTime)obj).ToBinary());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(Guid))
|
||||
{
|
||||
// Guid marker
|
||||
_writer.Write(Markers.Guid);
|
||||
_writer.Write(((Guid)obj).ToByteArray());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void WriteArray(Array array, SerializationContext context)
|
||||
{
|
||||
// Array marker
|
||||
_writer.Write(Markers.Array);
|
||||
|
||||
int objId = context.RegisterObject(array);
|
||||
Write7BitEncodedInt(objId);
|
||||
|
||||
Type elementType = array.GetType().GetElementType();
|
||||
Write7BitEncodedInt(FastBin.GetTypeId(elementType));
|
||||
Write7BitEncodedInt(array.Length);
|
||||
|
||||
foreach (var item in array)
|
||||
{
|
||||
WriteObject(item, elementType, context);
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteList(IList list, Type listType, SerializationContext context)
|
||||
{
|
||||
// List marker
|
||||
_writer.Write(Markers.List);
|
||||
|
||||
int objId = context.RegisterObject(list);
|
||||
Write7BitEncodedInt(objId);
|
||||
|
||||
Type elementType = listType.IsGenericType ? listType.GetGenericArguments()[0] : typeof(object);
|
||||
Write7BitEncodedInt(FastBin.GetTypeId(elementType));
|
||||
Write7BitEncodedInt(list.Count);
|
||||
|
||||
foreach (var item in list)
|
||||
{
|
||||
WriteObject(item, elementType, context);
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteDictionary(IDictionary dict, Type dictType, SerializationContext context)
|
||||
{
|
||||
// Dictionary marker
|
||||
_writer.Write(Markers.Dictionary);
|
||||
|
||||
int objId = context.RegisterObject(dict);
|
||||
Write7BitEncodedInt(objId);
|
||||
|
||||
Type keyType = typeof(object);
|
||||
Type valueType = typeof(object);
|
||||
|
||||
if (dictType.IsGenericType)
|
||||
{
|
||||
var args = dictType.GetGenericArguments();
|
||||
keyType = args[0];
|
||||
valueType = args[1];
|
||||
}
|
||||
|
||||
Write7BitEncodedInt(FastBin.GetTypeId(keyType));
|
||||
Write7BitEncodedInt(FastBin.GetTypeId(valueType));
|
||||
Write7BitEncodedInt(dict.Count);
|
||||
|
||||
foreach (DictionaryEntry entry in dict)
|
||||
{
|
||||
WriteObject(entry.Key, keyType, context);
|
||||
WriteObject(entry.Value, valueType, context);
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteComplexObject(object obj, Type actualType, Type declaredType, SerializationContext context)
|
||||
{
|
||||
// Complex object marker
|
||||
_writer.Write(Markers.ComplexObject);
|
||||
|
||||
int objId = context.RegisterObject(obj);
|
||||
Write7BitEncodedInt(objId);
|
||||
|
||||
// Write type info if polymorphic
|
||||
bool isPolymorphic = actualType != declaredType;
|
||||
_writer.Write(isPolymorphic);
|
||||
|
||||
if (isPolymorphic)
|
||||
{
|
||||
Write7BitEncodedInt(FastBin.GetTypeId(actualType));
|
||||
}
|
||||
|
||||
var fields = FastBin.GetFields(actualType);
|
||||
Write7BitEncodedInt(fields.Length);
|
||||
|
||||
foreach (var field in fields)
|
||||
{
|
||||
var value = field.GetValue(obj);
|
||||
WriteObject(value, field.FieldType, context);
|
||||
}
|
||||
}
|
||||
|
||||
private void Write7BitEncodedInt(int value)
|
||||
{
|
||||
uint v = (uint)value;
|
||||
while (v >= 0x80)
|
||||
{
|
||||
_writer.Write((byte)(v | 0x80));
|
||||
v >>= 7;
|
||||
}
|
||||
_writer.Write((byte)v);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_writer?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
20
EonaCat.FastBin/Markers.cs
Normal file
20
EonaCat.FastBin/Markers.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
public static class Markers
|
||||
{
|
||||
public const byte Null = 0;
|
||||
public const byte Reference = 254;
|
||||
public const byte Guid = 253;
|
||||
public const byte Array = 250;
|
||||
public const byte List = 249;
|
||||
public const byte Dictionary = 248;
|
||||
public const byte ComplexObject = 247;
|
||||
|
||||
}
|
||||
}
|
||||
15
EonaCat.FastBin/ReferenceEqualityComparer.cs
Normal file
15
EonaCat.FastBin/ReferenceEqualityComparer.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
internal class ReferenceEqualityComparer : IEqualityComparer<object>
|
||||
{
|
||||
public static readonly ReferenceEqualityComparer Instance = new ReferenceEqualityComparer();
|
||||
|
||||
public new bool Equals(object x, object y) => ReferenceEquals(x, y);
|
||||
public int GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj);
|
||||
}
|
||||
}
|
||||
24
EonaCat.FastBin/SerializationContext.cs
Normal file
24
EonaCat.FastBin/SerializationContext.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace EonaCat.FastBin
|
||||
{
|
||||
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||
// See the LICENSE file or go to https://EonaCat.com/license for full license details.
|
||||
internal class SerializationContext
|
||||
{
|
||||
private readonly Dictionary<object, int> _objectReferences = new Dictionary<object, int>(ReferenceEqualityComparer.Instance);
|
||||
private int _nextId = 1;
|
||||
|
||||
public bool TryGetObjectId(object obj, out int id)
|
||||
{
|
||||
return _objectReferences.TryGetValue(obj, out id);
|
||||
}
|
||||
|
||||
public int RegisterObject(object obj)
|
||||
{
|
||||
int id = _nextId++;
|
||||
_objectReferences[obj] = id;
|
||||
return id;
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
EonaCat.ico
Normal file
BIN
EonaCat.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 248 KiB |
BIN
EonaCat.png
Normal file
BIN
EonaCat.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 88 KiB |
213
LICENSE
213
LICENSE
@@ -1,73 +1,204 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
https://EonaCat.com/license/
|
||||
|
||||
1. Definitions.
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
OF SOFTWARE BY EONACAT (JEROEN SAEY)
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
1. Definitions.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
Copyright 2025 EonaCat
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
301
README.md
301
README.md
@@ -1,3 +1,302 @@
|
||||
# EonaCat.FastBin
|
||||
# EonaCat.FastBin
|
||||
|
||||
A blazingly fast, enterprise-grade binary serialization library for .NET with built-in networking capabilities.
|
||||
|
||||
## 🚀 Features
|
||||
|
||||
- **⚡ Ultra-fast** - Binary format optimized for speed, outperforms JSON and MessagePack
|
||||
- **🔄 Complete object graph support** - Handles nested objects, circular references, and polymorphism
|
||||
- **📦 Zero configuration** - Works with any type out of the box
|
||||
- **🌐 Built-in networking** - TCP client/server with RPC support included
|
||||
- **🎯 Type-safe** - Strongly-typed API with full generic support
|
||||
- **🔒 Thread-safe** - Safe for concurrent serialization/deserialization
|
||||
- **📱 Cross-platform** - .NET Standard 2.1 compatible
|
||||
|
||||
## 📊 Performance
|
||||
|
||||
EonaCat.FastBin uses several optimization techniques to achieve superior performance:
|
||||
|
||||
- **Binary format** - No text parsing overhead
|
||||
- **7-bit integer encoding** - Compact representation of small numbers
|
||||
- **Type caching** - Reflection performed only once per type
|
||||
- **Reference tracking** - Objects serialized once, referenced thereafter
|
||||
- **Zero-copy operations** - Direct memory access where possible
|
||||
|
||||
## 🎯 Quick Start
|
||||
|
||||
### Basic Serialization
|
||||
|
||||
```csharp
|
||||
using EonaCat.FastBin;
|
||||
|
||||
// Serialize any object
|
||||
var user = new User { Id = 1, Name = "Brasser", Email = "brasser@example.com" };
|
||||
byte[] data = EonaCat.FastBin.Serialize(user);
|
||||
|
||||
// Deserialize back
|
||||
var restored = EonaCat.FastBin.Deserialize<User>(data);
|
||||
```
|
||||
|
||||
### Complex Objects
|
||||
|
||||
```csharp
|
||||
// Works with nested objects
|
||||
var order = new Order
|
||||
{
|
||||
OrderId = Guid.NewGuid(),
|
||||
TotalAmount = 299.99m,
|
||||
Items = new List<OrderItem>
|
||||
{
|
||||
new OrderItem { ProductName = "Laptop", Quantity = 1, Price = 299.99m }
|
||||
}
|
||||
};
|
||||
|
||||
byte[] data = EonaCat.FastBin.Serialize(order);
|
||||
var restored = EonaCat.FastBin.Deserialize<Order>(data);
|
||||
```
|
||||
|
||||
### Collections
|
||||
|
||||
```csharp
|
||||
// Lists
|
||||
var users = new List<User> { user1, user2, user3 };
|
||||
byte[] data = EonaCat.FastBin.Serialize(users);
|
||||
|
||||
// Dictionaries
|
||||
var userMap = new Dictionary<int, User>
|
||||
{
|
||||
[1] = user1,
|
||||
[2] = user2
|
||||
};
|
||||
byte[] data2 = EonaCat.FastBin.Serialize(userMap);
|
||||
|
||||
// Arrays
|
||||
var userArray = new User[] { user1, user2 };
|
||||
byte[] data3 = EonaCat.FastBin.Serialize(userArray);
|
||||
```
|
||||
|
||||
### Circular References
|
||||
|
||||
```csharp
|
||||
// Self-referencing objects work automatically
|
||||
var manager = new User { Id = 1, Name = "Manager" };
|
||||
var employee = new User { Id = 2, Name = "Brasser", Manager = manager };
|
||||
manager.Manager = manager; // Circular reference
|
||||
|
||||
byte[] data = EonaCat.FastBin.Serialize(employee);
|
||||
var restored = EonaCat.FastBin.Deserialize<User>(data);
|
||||
|
||||
// Reference integrity maintained
|
||||
Console.WriteLine(ReferenceEquals(restored.Manager, restored.Manager.Manager)); // True
|
||||
```
|
||||
|
||||
### Polymorphism
|
||||
|
||||
```csharp
|
||||
// Handles polymorphic types automatically
|
||||
object[] items = new object[]
|
||||
{
|
||||
"A string",
|
||||
42,
|
||||
new User { Id = 1, Name = "Brasser" },
|
||||
new Order { OrderId = Guid.NewGuid() }
|
||||
};
|
||||
|
||||
byte[] data = EonaCat.FastBin.Serialize(items);
|
||||
var restored = EonaCat.FastBin.Deserialize<object[]>(data);
|
||||
|
||||
// Types preserved correctly
|
||||
Console.WriteLine(restored[0].GetType()); // System.String
|
||||
Console.WriteLine(restored[2].GetType()); // User
|
||||
```
|
||||
|
||||
## 🌐 Networking
|
||||
|
||||
### Server Setup
|
||||
|
||||
```csharp
|
||||
var server = new FastServer();
|
||||
|
||||
// Register handlers
|
||||
server.RegisterHandler<GetUserRequest, User>("GetUser", request =>
|
||||
{
|
||||
// Your business logic here
|
||||
return database.GetUser(request.UserId);
|
||||
});
|
||||
|
||||
server.RegisterHandler<CreateOrderRequest, CreateOrderResponse>("CreateOrder", async request =>
|
||||
{
|
||||
// Async handlers supported
|
||||
var order = await orderService.CreateOrderAsync(request);
|
||||
return new CreateOrderResponse { OrderId = order.Id, Message = "Success" };
|
||||
});
|
||||
|
||||
// Start server
|
||||
await server.StartAsync(5000);
|
||||
```
|
||||
|
||||
### Client Usage
|
||||
|
||||
```csharp
|
||||
using (var client = new FastClient())
|
||||
{
|
||||
await client.ConnectAsync("localhost", 5000);
|
||||
|
||||
// Make RPC calls
|
||||
var user = await client.CallAsync<GetUserRequest, User>(
|
||||
"GetUser",
|
||||
new GetUserRequest { UserId = 123 }
|
||||
);
|
||||
|
||||
var response = await client.CallAsync<CreateOrderRequest, CreateOrderResponse>(
|
||||
"CreateOrder",
|
||||
new CreateOrderRequest
|
||||
{
|
||||
UserId = 123,
|
||||
Items = orderItems
|
||||
}
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 📋 Supported Types
|
||||
|
||||
### Primitives
|
||||
- All numeric types: `byte`, `sbyte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `float`, `double`, `decimal`
|
||||
- `bool`, `char`, `string`
|
||||
- `DateTime`, `Guid`
|
||||
- Enums
|
||||
|
||||
### Collections
|
||||
- Arrays: `T[]`
|
||||
- Lists: `List<T>`, `IList`, `IList<T>`
|
||||
- Dictionaries: `Dictionary<K,V>`, `IDictionary`, `IDictionary<K,V>`
|
||||
|
||||
### Complex Types
|
||||
- Classes (public and non-public fields)
|
||||
- Structs
|
||||
- Nested objects
|
||||
- Generic types
|
||||
- Polymorphic types
|
||||
- Self-referencing objects
|
||||
- Circular references
|
||||
|
||||
## 🔧 Advanced Usage
|
||||
|
||||
### Custom Domain Models
|
||||
|
||||
```csharp
|
||||
public class Customer
|
||||
{
|
||||
public int Id;
|
||||
public string Name;
|
||||
public string Email;
|
||||
public DateTime CreatedAt;
|
||||
public Address ShippingAddress;
|
||||
public List<Order> Orders;
|
||||
public Customer ReferredBy; // Self-reference supported
|
||||
}
|
||||
|
||||
public class Address
|
||||
{
|
||||
public string Street;
|
||||
public string City;
|
||||
public string ZipCode;
|
||||
public string Country;
|
||||
}
|
||||
```
|
||||
|
||||
No attributes or special configuration needed - just define your classes normally!
|
||||
|
||||
### Error Handling (Networking)
|
||||
|
||||
```csharp
|
||||
try
|
||||
{
|
||||
var result = await client.CallAsync<Request, Response>("Route", request);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Handle network errors, deserialization errors, or handler exceptions
|
||||
Console.WriteLine($"RPC failed: {ex.Message}");
|
||||
}
|
||||
```
|
||||
|
||||
### Server Shutdown
|
||||
|
||||
```csharp
|
||||
// Graceful shutdown
|
||||
server.Stop();
|
||||
```
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
### Binary Format
|
||||
|
||||
EonaCat.FastBin uses a compact binary format with the following features:
|
||||
|
||||
1. **Type markers** - Single byte to identify data type
|
||||
2. **7-bit encoding** - Variable-length integers for efficiency
|
||||
3. **Reference tracking** - Objects assigned IDs, referenced by ID on subsequent encounters
|
||||
4. **Type polymorphism** - Actual type stored when different from declared type
|
||||
5. **Field ordering** - Consistent ordering by name for versioning
|
||||
|
||||
### Networking Protocol
|
||||
|
||||
1. **Message framing** - 4-byte length prefix
|
||||
2. **Request/Response** - Structured messages with route and data
|
||||
3. **Error handling** - Exceptions marshaled back to client
|
||||
4. **Type safety** - Generic request/response types
|
||||
|
||||
## ⚠️ Limitations & Considerations
|
||||
|
||||
- **Private fields** - Serializes all fields (public and private)
|
||||
- **Properties** - Only backing fields are serialized
|
||||
- **Versioning** - Adding/removing fields requires redeployment (no built-in versioning)
|
||||
- **Security** - No encryption built-in (use TLS/SSL at transport layer)
|
||||
- **Large objects** - Keep network messages under 2GB (int.MaxValue)
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
The included example application demonstrates:
|
||||
|
||||
1. ✅ Basic serialization of primitives and collections
|
||||
2. ✅ Complex nested object graphs
|
||||
3. ✅ Self-referencing and circular references
|
||||
4. ✅ Polymorphic type handling
|
||||
5. ✅ Client-server RPC communication
|
||||
|
||||
## 🔄 Migration Guide
|
||||
|
||||
### From JSON.NET
|
||||
|
||||
```csharp
|
||||
// Before (JSON.NET)
|
||||
string json = JsonConvert.SerializeObject(obj);
|
||||
var restored = JsonConvert.DeserializeObject<T>(json);
|
||||
|
||||
// After (EonaCat.FastBin)
|
||||
byte[] data = FastBin.Serialize(obj);
|
||||
var restored = FastBin.Deserialize<T>(data);
|
||||
```
|
||||
|
||||
### From MessagePack
|
||||
|
||||
```csharp
|
||||
// Before (MessagePack)
|
||||
byte[] data = MessagePackSerializer.Serialize(obj);
|
||||
var restored = MessagePackSerializer.Deserialize<T>(data);
|
||||
|
||||
// After (EonaCat.FastBin) - Same API!
|
||||
byte[] data = FastBin.Serialize(obj);
|
||||
var restored = FastBin.Deserialize<T>(data);
|
||||
```
|
||||
|
||||
## 📝 Best Practices
|
||||
|
||||
1. **Reuse clients** - Create one `FastClient` per connection, reuse for multiple calls
|
||||
2. **Dispose properly** - Always dispose clients: `using (var client = new FastClient())`
|
||||
3. **Handler registration** - Register all handlers before calling `StartAsync()`
|
||||
4. **Error handling** - Always wrap RPC calls in try-catch
|
||||
5. **Thread safety** - `FastBin` class is thread-safe, instances are not
|
||||
6. **Network timeout** - Implement timeouts at the TCP socket level if needed
|
||||
Reference in New Issue
Block a user