#pragma once #include namespace sccl { // 实现类似于std::span的功能,将字节数组转换为类型数组 // 采用Vector的各种接口,区别在于ByteSpanVector对data元素为直接操作,而std::vector为拷贝 template class ByteSpanVector { public: // 构造函数,接受一个指向数据的指针和数据的容量 ByteSpanVector(void* data, size_t capacity) : data_(reinterpret_cast(data)), capacity_(capacity / sizeof(T)), size_(0) {} // 提供一个data()函数,返回指向数据的指针 T* data() const { return data_; } // 提供一个size()函数,返回当前已经写入的数据的数量 size_t size() const { return size_; } // 提供一个capacity()函数,返回预留给数据的最大空间 size_t capacity() const { return capacity_; } // 提供一个空的检查函数 bool empty() const { return size_ == 0; } // 提供一个检查是否已满的函数 bool full() const { return size_ == capacity_; } // 提供一个在末尾添加元素的函数 void push_back(const T& value) { if(size_ < capacity_) { new(data_ + size_) T(value); ++size_; } else { // 处理容量不足的情况,例如抛出异常或扩展容量 throw std::overflow_error("ByteSpanVector push_back capacity exceeded"); } } // 提供一个访问指定索引处元素的函数,返回指针 T* operator[](size_t index) { if(index < size_) { return &(data_[index]); } else { return nullptr; // 返回空指针 } } const T* operator[](size_t index) const { if(index < size_) { return &(data_[index]); } else { return nullptr; // 返回空指针 } } private: T* data_; size_t capacity_; size_t size_; }; template class ByteSpanArray { public: // 构造函数,接受一个指向数据的void*指针和总的字节大小 ByteSpanArray(void* data, size_t size) : data_(reinterpret_cast(data)), size_(size / sizeof(T)) {} // 提供一个size()函数,返回当前已经写入的数据的数量 size_t size() const { return size_; } // 提供一个函数来返回数据块的起始地址 T* data() const { return data_; } // 提供一个访问指定索引处元素的函数,返回T*类型的数据,或者在索引超出范围时返回空指针nullptr T* operator[](size_t index) { if(index < size_) { return data_ + index; } else { return nullptr; } } const T* operator[](size_t index) const { if(index < size_) { return data_ + index; } else { return nullptr; } } private: T* data_; size_t size_; }; } // namespace sccl