ThakeeNathees / pocketlang

A lightweight, fast embeddable scripting language.
https://thakeenathees.github.io/pocketlang/
MIT License
1.52k stars 78 forks source link

[ref] ByteBuffer implementation detail #78

Open ThakeeNathees opened 3 years ago

ThakeeNathees commented 3 years ago

How a ByteBuffer works in pocketlang

Use this thread to discuss how pocketlang's buffer works

A byte buffer is a heap allocated array of bytes (uint8_t). Here is the declaration of it.

typedef struct {
  uint8_t* data;     // Pointer to the heap allocated array.
  uint32_t count;    // Number of elements in the array.
  uint32_t capacity; // The allocated (reserved) size.
} ByteBuffer;

Every time we write a byte into the buffer, the value will be "appended" at the end of the buffer and the count will increase.

              Un initialized memory
                  .---------.
        [ 42 12 65 ? ? ? ? ? ]
The count is 3 --^         ^-- The capacity is 8

If the buffer is filled with values it'll resize itself to a larger size. (by default it'll double it size)

                     Un initialized memory
                        .---------------.
[ 42 12 65 78 10 2 55 68 ? ? ? ? ? ? ? ? ]
      The count is 8 --^               ^-- The capacity is 16

Here are the functions for the byte buffer defined in cli/utils.h

// Initialize a new buffer int instance.
void byteBufferInit(ByteBuffer* buffer);

// Clears the allocated elements from the VM's realloc function.
void byteBufferClear(ByteBuffer* buffer);

// Ensure the capacity is greater than [size], if not resize.
void byteBufferReserve(ByteBuffer* buffer, size_t size);

// Fill the buffer at the end of it with provided data if the capacity
// isn't enough using VM's realloc function.
void byteBufferFill(ByteBuffer* buffer, uint8_t data, int count);

// Write to the buffer with provided data at the end of the buffer.
void byteBufferWrite(ByteBuffer* buffer, uint8_t data);

// Add all the characters to the buffer, byte buffer can also be used as a
// buffer to write string (like a string stream). Note that this will not
// add a null byte '\0' at the end.
void byteBufferAddString(ByteBuffer* buffer, const char* str, uint32_t length);

These comments explain what the function does, for how it does read the comments inside the function implementations at the cli/utils.c. And if you have any questions, suggestions or improvements, feel free to use this thread to discuss.

xSavitar commented 3 years ago

Thanks for summarizing the architecture of the byte buffer so beautifully. Makes a lot of sense. :]