Skip to content

[C#] String extraction/setting impossible without memory allocation with current API #729

Closed
@rca22

Description

@rca22

Using your example in the documentation

// Create a vehicle code of the correct encoding
VehicleCode = Encoding.GetEncoding(Car.VehicleCodeCharacterEncoding).GetBytes("abcdef");
car.SetVehicleCode(vehicleCode, 0); // second argument is offset

This is terrible. It defeats the whole point of SBE because it uses a method GetBytes() which allocates a new array of bytes, and then copies that to the direct buffer we are targeting.
We should be using this method to get the number of bytes which a particular string would generate.
We should then check that against the size available, and use
this method to write to the underlying buffer.

In order to do this, we need to be able to access the underlying byte array for the DirectBuffer, and it would be best to do this through support in the generated classes.

I can't see any way of writing a string into one of the generated classes without having auxiliary buffers of bytes hanging around if I want to avoid allocations, the way the accessor methods are currently provided.

Similarly to read a string, your example is

var vehicleCode = new byte[Car.VehicleCodeLength];
car.GetVehicleCode(vehicleCode, 0);
sb.Append(Encoding.GetEncoding(Car.VehicleCodeCharacterEncoding).GetString(vehicleCode, 0, Car.VehicleCodeLength));

Which suffers from the same problem...
We should be using this method to generate a string directly (perhaps having first looked through the buffer for a terminating \0 character to establish how many of the available bytes actually comprise the string we want to extract)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions