Representing strings with variable (but short, bounded) length

I have some strings I would like to be able to parse without heap allocations.

I know ahead of time that the strings will be a maximum length of 127 bytes.

What type can I use that can be:

  1. Stack allocated
  2. Have string length information?

here is some pseudocode of what I would like to accomplish

pub fn get_string(port: *Port) ![128]u8 {
    const string_length: u8 = port.get_string_length();
    const buffer: [128]u8 = undefined;
    try port.read_string(&buffer[0..string_length]);
}

Perhaps I should use [128]?u8 ?

Or some sentinel stuff?

I usually just create a struct that holds both the buffer and the length:

const String = struct {
    buf: [127]u8,
    len: u7,
};

Or you can use std.BoundedArray.

1 Like

You can probably use a RingBuffer for that too, if you just need to read/write to a stack allocated slice that works well too.

Depends what you need to do with them after. You can wrap up arrays in a fixed buffer stream as well as other suggestions here.

You can also just take slices of an array backing and set the Len to the string Len.

The fact that this is one byte over two cache lines is causing me almost physical pain. If there’s a need for a zero terminator on the strings, then sure, but if not, a [127]u8 meets the stated goal, and the whole struct will Tetris into the rest of the program much better.

6 Likes

Could also pass a stack allocated buffer into the function, and have the function return a slice []u8 which would represent the part of the buffer actually used.

3 Likes