container.h 2.84 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#pragma once

#include <stdint.h>

namespace sccl {

// 实现类似于std::span的功能,将字节数组转换为类型数组
// 采用Vector的各种接口,区别在于ByteSpanVector对data元素为直接操作,而std::vector为拷贝
template <typename T>
class ByteSpanVector {
public:
    // 构造函数,接受一个指向数据的指针和数据的容量
    ByteSpanVector(void* data, size_t capacity) : data_(reinterpret_cast<T*>(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 <typename T>
class ByteSpanArray {
public:
    // 构造函数,接受一个指向数据的void*指针和总的字节大小
    ByteSpanArray(void* data, size_t size) : data_(reinterpret_cast<T*>(data)), size_(size / sizeof(T)) {}

    // 提供一个size()函数,返回当前已经写入的数据的数量
    size_t size() const { return size_; }

73
74
75
    // 提供一个函数来返回数据块的起始地址
    T* data() const { return data_; }

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    // 提供一个访问指定索引处元素的函数,返回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