Skip to content

Type System

LoSkroefie edited this page Jan 19, 2025 · 1 revision

Type System

Overview

FLEXON's type system is designed to be robust, extensible, and efficient. It supports a wide range of built-in types and allows for custom type definitions.

Built-in Types

Primitive Types

Type C# Type Description Example
Null null Null value null
Boolean bool True/false value true, false
Integer int 32-bit signed integer 42
Long long 64-bit signed integer 9223372036854775807
Float float 32-bit floating point 3.14f
Double double 64-bit floating point 3.14159265359
String string UTF-8 encoded text "Hello, World!"
Binary byte[] Raw binary data [0x00, 0xFF]

Complex Types

Arrays

// Fixed-type arrays
int[] numbers = [1, 2, 3];
string[] names = ["Alice", "Bob"];

// Object arrays
object[] mixed = [1, "two", true];

// Multi-dimensional arrays
int[,] matrix = {{1, 2}, {3, 4}};

Collections

// Lists
List<int> numbers = new() { 1, 2, 3 };

// Dictionaries
Dictionary<string, object> dict = new()
{
    ["name"] = "John",
    ["age"] = 30
};

// Sets
HashSet<string> uniqueNames = new() { "Alice", "Bob" };

Special Types

DateTime

// UTC DateTime
DateTime utcNow = DateTime.UtcNow;

// Local DateTime
DateTime localTime = DateTime.Now;

// Custom timezone
DateTimeOffset pacific = DateTimeOffset.Now.ToOffset(
    TimeSpan.FromHours(-8));

GUID

// Generate new GUID
Guid id = Guid.NewGuid();

// Parse from string
Guid parsed = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");

Custom Types

Defining Custom Types

[FlexonType(TypeCode = 0x0A)]
public class GeoPoint : IFlexonType
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }

    public void Serialize(FlexonWriter writer)
    {
        writer.WriteDouble(Latitude);
        writer.WriteDouble(Longitude);
    }

    public void Deserialize(FlexonReader reader)
    {
        Latitude = reader.ReadDouble();
        Longitude = reader.ReadDouble();
    }
}

Registering Custom Types

// Global registration
FlexonConfiguration.RegisterType<GeoPoint>();

// Local registration
var options = new FlexonOptions();
options.RegisterType<GeoPoint>();
var serializer = new FlexonSerializer(options);

Type Versioning

[FlexonType(TypeCode = 0x0A, Version = 2)]
public class GeoPoint : IFlexonType
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public double? Altitude { get; set; }  // Added in version 2

    public void Serialize(FlexonWriter writer)
    {
        writer.WriteDouble(Latitude);
        writer.WriteDouble(Longitude);
        writer.WriteNullableDouble(Altitude);
    }

    public void Deserialize(FlexonReader reader)
    {
        Latitude = reader.ReadDouble();
        Longitude = reader.ReadDouble();
        if (reader.Version >= 2)
            Altitude = reader.ReadNullableDouble();
    }
}

Type Conversion

Implicit Conversions

// Numeric conversions
int i = 42;
long l = i;      // int -> long
double d = i;    // int -> double

// String conversions
string s = i.ToString();  // number -> string

Explicit Conversions

// Using Convert
int i = Convert.ToInt32("42");
double d = Convert.ToDouble("3.14");
bool b = Convert.ToBoolean("true");

// Using Parse
DateTime dt = DateTime.Parse("2025-01-19");
Guid g = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");

Custom Conversions

public class Temperature : IFlexonConvertible
{
    public double Celsius { get; set; }

    public static Temperature FromKelvin(double kelvin)
    {
        return new Temperature { Celsius = kelvin - 273.15 };
    }

    public double ToKelvin()
    {
        return Celsius + 273.15;
    }
}

Type Extensions

Extension Methods

public static class TypeExtensions
{
    public static byte[] ToFlexon<T>(this T obj)
    {
        var serializer = new FlexonSerializer();
        return serializer.Serialize(obj);
    }

    public static T FromFlexon<T>(this byte[] data)
    {
        var serializer = new FlexonSerializer();
        return serializer.Deserialize<T>(data);
    }
}

Custom Attributes

[AttributeUsage(AttributeTargets.Property)]
public class FlexonIgnoreAttribute : Attribute
{
}

[AttributeUsage(AttributeTargets.Property)]
public class FlexonNameAttribute : Attribute
{
    public string Name { get; }
    public FlexonNameAttribute(string name) => Name = name;
}

Type Safety

Validation

public class Person
{
    [Required]
    public string Name { get; set; }

    [Range(0, 150)]
    public int Age { get; set; }

    [EmailAddress]
    public string Email { get; set; }
}

Schema Validation

var schema = @"{
    'type': 'object',
    'properties': {
        'name': { 'type': 'string' },
        'age': { 
            'type': 'integer',
            'minimum': 0,
            'maximum': 150
        },
        'email': {
            'type': 'string',
            'format': 'email'
        }
    },
    'required': ['name', 'age']
}";

var options = new FlexonOptions
{
    EnableValidation = true,
    Schema = FlexonSchema.FromString(schema)
};

Performance Considerations

Memory Layout

// Struct for value types
public struct Point
{
    public double X;
    public double Y;
}

// Class for reference types
public class ComplexObject
{
    public string Name;
    public List<Point> Points;
}

Buffer Management

// Use buffer pooling
var options = new FlexonOptions
{
    UsePooledBuffers = true,
    BufferSize = 8192
};

using var buffer = new FlexonBuffer(options);

Optimization Tips

  1. Use value types for small objects
  2. Implement custom serialization for complex types
  3. Use buffer pooling for large datasets
  4. Consider compression for network transfer
  5. Profile and benchmark your code

Best Practices

  1. Type Design

    • Keep types simple and focused
    • Use appropriate data types
    • Document type behavior
  2. Validation

    • Always validate input
    • Use schema validation
    • Handle errors appropriately
  3. Performance

    • Use buffer pooling
    • Implement custom serialization
    • Profile your code
  4. Maintenance

    • Version your types
    • Document changes
    • Write tests

Clone this wiki locally