jamescourtney / FlatSharp

Fast, idiomatic C# implementation of Flatbuffers
Apache License 2.0
510 stars 51 forks source link

Re-Evaluate Value Type Options #191

Closed jamescourtney closed 3 years ago

jamescourtney commented 3 years ago

This is an increasingly common request, so this tracks re-evaluation of exposing structs as value types.

What won't work?

Is this better or worse than the object pooling approach?

jamescourtney commented 3 years ago

Alternatively, this could be a FlatSharp v6 feature and all FlatBuffer structs could be exposed as value types.

jamescourtney commented 3 years ago

This design is a little complicated. The canonical FlatBuffer library uses value structs for all operations, and that is OK because all objects are FlatBuffers, and hence have a backing buffer. Flatsharp takes the view that some objects may be backed by buffers, but others may not be. This is abstracted away through inheritance.

Value-type structs (value structs) prove to be an awkward addition to FlatSharp, because C# Structs are not inheritable (using an interface would induce boxing and defeat the point), so FlatSharp's normal codegen approaches fall short here.

However, structs have the distinguishing feature of being GC-friendly, and so there is some value in adding them. However, it's worth enumerating the constraints first.

Tentative design:

        [FlatBufferStruct, StructLayout(LayoutKind.Explicit, Size = 16)]
        public struct SimpleValueStruct
        {
            [FieldOffset(0)]
            public long Long;

            [FieldOffset(8)]
            public byte Byte;

            [FieldOffset(12)]
            public uint Uint;
        }