codac 1.5.6
Loading...
Searching...
No Matches
codac2_serialize.h
Go to the documentation of this file.
1
9
10#pragma once
11
12#include <fstream>
13#include "codac2_Vector.h"
14#include "codac2_SampledTraj.h"
15
16namespace codac2
17{
18 // Trivial types (int, float, double...)
19
20 template <typename T>
21 requires (std::is_trivially_copyable_v<T>)
22 void serialize(std::ofstream& f, const T& x)
23 {
24 f.write(reinterpret_cast<const char*>(&x), sizeof(T));
25 }
26
27 template <typename T>
28 requires (std::is_trivially_copyable_v<T>)
29 void deserialize(std::ifstream& f, T& x)
30 {
31 f.read(reinterpret_cast<char*>(&x), sizeof(T));
32 }
33
34 // Vector
35
36 template<typename T>
37 void serialize(std::ofstream& f, const Eigen::Matrix<T,-1,1>& x)
38 {
39 Index size = x.size();
40 f.write(reinterpret_cast<const char*>(&size), sizeof(T));
41 for(Index i = 0 ; i < size ; i++)
42 serialize(f,x[i]);
43 }
44
45 template<typename T>
46 void deserialize(std::ifstream& f, Eigen::Matrix<T,-1,1>& x)
47 {
48 Index size;
49 f.read(reinterpret_cast<char*>(&size), sizeof(T));
50 x.resize(size);
51 for(Index i = 0 ; i < size ; i++)
52 deserialize(f,x[i]);
53 }
54
55 // Matrix
56
57 template<typename T>
58 void serialize(std::ofstream& f, const Eigen::Matrix<T,-1,-1>& x)
59 {
60 Index r = x.rows(), c = x.cols();
61 f.write(reinterpret_cast<const char*>(&r), sizeof(T));
62 f.write(reinterpret_cast<const char*>(&c), sizeof(T));
63 for(Index i = 0 ; i < r ; i++)
64 for(Index j = 0 ; j < c ; j++)
65 serialize(f,x(i,j));
66 }
67
68 template<typename T>
69 void deserialize(std::ifstream& f, Eigen::Matrix<T,-1,-1>& x)
70 {
71 Index r, c;
72 f.read(reinterpret_cast<char*>(&r), sizeof(T));
73 f.read(reinterpret_cast<char*>(&c), sizeof(T));
74 x.resize(r,c);
75 for(Index i = 0 ; i < r ; i++)
76 for(Index j = 0 ; j < c ; j++)
77 deserialize(f,x(i,j));
78 }
79
80 // SampledTraj<T>
81
82 template <typename T>
83 void serialize(std::ofstream& f, const SampledTraj<T>& x)
84 {
85 Index size = x.nb_samples();
86 f.write(reinterpret_cast<const char*>(&size), sizeof(size));
87
88 for(const auto& [ti, xi] : x)
89 {
90 serialize(f, ti);
91 serialize(f, xi);
92 }
93 }
94
95 template <typename T>
96 void deserialize(std::ifstream& f, SampledTraj<T>& x)
97 {
98 Index size;
99 x.clear();
100 f.read(reinterpret_cast<char*>(&size), sizeof(size));
101
102 for(Index i = 0 ; i < size ; i++)
103 {
104 double ti; deserialize(f,ti);
105 T xi; deserialize(f,xi);
106 x.set(ti,xi);
107 }
108 }
109}