Skip to content

SmallVector: Core SBO storage and basic operations #71

Description

@jsrivaya

Parent

Closes part of #5.

Summary

Implement the core small buffer optimization (SBO) storage and basic operations for loon::SmallVector<T, N>.

Scope

This is the foundational issue. All other SmallVector issues depend on this.

Inline storage layout

template <typename T, size_t N>
class SmallVector {
    alignas(T) std::byte inline_storage[sizeof(T) * N];
    T*       heap_ptr  = nullptr;
    uint32_t size_     = 0;
    uint32_t capacity_ = N;

    T* data() { return is_small() ? reinterpret_cast<T*>(inline_storage) : heap_ptr; }
    bool is_small() const { return heap_ptr == nullptr; }
};

Using alignas(T) ensures the inline buffer is correctly aligned for any T, including over-aligned types.

Operations in scope

  • push_back(const T&) — copy into next slot; trigger heap transition if at capacity
  • pop_back() — destroy last element, decrement size
  • operator[](size_t) — bounds-unchecked access
  • at(size_t) — bounds-checked access
  • data() — raw pointer to storage
  • size(), capacity(), empty(), is_small()
  • Default constructor, destructor (destroy live elements, free heap if needed)
  • clear() — destroy all elements, reset size; keep storage

Heap transition

When size_ == capacity_ and another element is pushed:

  1. Allocate new heap block (2x growth)
  2. Move all elements from inline storage to heap
  3. Destroy originals in inline storage
  4. Set heap_ptr, update capacity_

Out of scope for this issue

  • Copy/move constructors and assignment (#SmallVector-semantics)
  • Iterators (#SmallVector-iterators)
  • insert/emplace/erase (#SmallVector-insert)
  • Exception safety guarantees (#SmallVector-exceptions)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions