-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvecstore.h
107 lines (93 loc) · 2.97 KB
/
vecstore.h
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// A quick and dirty unified vector serialization/deserialization (C) Dmitry 'sciloaf' Solovyev, 2024
#pragma once
#include <vector>
#include <string>
#include <deque>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
template <class T> class vector_storage {
public:
static size_t store(const std::vector<T> & vec, FILE* f) {
uint64_t sz = vec.size();
size_t r = fwrite(&sz,sizeof(sz),1,f) * sizeof(uint64_t);
r += fwrite(vec.data(),sizeof(T),sz,f) * sizeof(T);
return r;
}
static void* store(const std::vector<T> & vec, void* mem) {
if (!mem) return nullptr;
uint64_t* sptr = reinterpret_cast<uint64_t*> (mem);
*sptr = vec.size();
T* ptr = reinterpret_cast<T*> (sptr+1);
for (auto & i: vec) *ptr++ = i;
return ptr;
}
static std::vector<T> load(FILE* f) {
std::vector<T> vec;
uint64_t sz;
if (fread(&sz,sizeof(sz),1,f)) {
vec.resize(sz);
if (fread(vec.data(),sizeof(T),sz,f) != sz)
vec.clear();
}
return vec;
}
static std::vector<T> load(void** mem) {
std::vector<T> vec;
if ((!mem) || !(*mem)) return vec;
uint64_t* sptr = reinterpret_cast<uint64_t*> (*mem);
vec.resize(*sptr);
T* ptr = reinterpret_cast<T*> (sptr+1);
memcpy(vec.data(),ptr,sizeof(T) * (*sptr));
*mem = ptr + (*sptr);
return vec;
}
static std::vector<T> from_string(const std::string & str) {
std::vector<T> r;
for (auto & i: str) r.push_back(i); // implicitly casted, hopefully ok ;)
return r;
}
static std::string to_string(const std::vector<T> & vec) {
std::string r;
for (auto & i: vec) r.push_back(i);
return r;
}
static std::vector<T> from_pool(uint8_t* data, size_t size) {
std::vector<T> r;
while (size--) {
r.push_back(*((T*)data));
data += sizeof(T);
}
return r;
}
static uint8_t* to_pool(const std::vector<T> & vec) {
uint8_t* out = (uint8_t*)malloc(sizeof(T) * vec.size());
if (out) {
uint8_t* pos = out;
for (auto & i : vec) {
*((T*)pos) = i;
pos += sizeof(T);
}
}
return out;
}
static std::vector<T> from_deque(const std::deque<T> & deq) {
std::vector<T> r;
for (auto & i: deq) r.push_back(i);
return r;
}
static std::deque<T> to_deque(const std::vector<T> & vec) {
std::deque<T> r;
for (auto & i: vec) r.push_back(i);
return r;
}
static size_t size(const std::vector<T> & vec) {
return vec.size() * sizeof(T) + sizeof(uint64_t);
}
static size_t size(const std::string & str) {
return str.size() * sizeof(T) + sizeof(uint64_t);
}
static size_t size(const std::deque<T> & deq) {
return deq.size() * sizeof(T) + sizeof(uint64_t);
}
};