Carotid 0.1.1
Loading...
Searching...
No Matches
Utility.h
Go to the documentation of this file.
1#ifndef CAROTID_UTILITY_H
2#define CAROTID_UTILITY_H
3
4#include <Eigen/Dense>
5#include <expected>
6#include <filesystem>
7#include <fstream>
8
9namespace carotid {
10
11using Path = std::filesystem::path;
12
13template <typename T>
14using Mat = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;
15
16template <typename T>
17using Vec = Eigen::Matrix<T, Eigen::Dynamic, 1>;
18
19template <typename T>
20[[nodiscard]] std::expected<Mat<T>, std::ios_base::failure>
21loadBinaryIntoMatrix(const Path &filename, int rows, int cols) {
22 std::ifstream in(filename, std::ios::binary);
23 if (!in.is_open()) {
24 return std::unexpected(
25 std::ios_base::failure("File not found or could not be opened.",
26 std::make_error_code(std::errc::io_error)));
27 }
28
29 Mat<T> mat(rows, cols);
30
31 in.read(reinterpret_cast<char *>(mat.data()), rows * cols * sizeof(T));
32 if (!in) {
33 return std::unexpected(std::ios_base::failure(
34 "Failed to read the entire file.", std::make_error_code(std::errc::io_error)));
35 }
36
37 return mat;
38}
39
40template <typename T>
41[[nodiscard]] std::expected<Vec<T>, std::ios_base::failure>
42loadBinaryIntoVector(const Path &filename, int n) {
43 std::ifstream in(filename, std::ios::binary);
44 if (!in.is_open()) {
45 return std::unexpected(
46 std::ios_base::failure("File not found or could not be opened.",
47 std::make_error_code(std::errc::io_error)));
48 }
49
50 Vec<T> vec(n);
51
52 in.read(reinterpret_cast<char *>(vec.data()), n * sizeof(T));
53 if (!in) {
54 return std::unexpected(std::ios_base::failure(
55 "Failed to read the entire file.", std::make_error_code(std::errc::io_error)));
56 }
57
58 return vec;
59}
60
61} // namespace carotid
62
63#endif // CAROTID_UTILITY_H
Definition IdentityGenerator.h:6
Eigen::Matrix< T, Eigen::Dynamic, 1 > Vec
Definition Utility.h:17
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > Mat
Definition Utility.h:14
std::expected< Mat< T >, std::ios_base::failure > loadBinaryIntoMatrix(const Path &filename, int rows, int cols)
Definition Utility.h:21
std::filesystem::path Path
Definition Utility.h:11
std::expected< Vec< T >, std::ios_base::failure > loadBinaryIntoVector(const Path &filename, int n)
Definition Utility.h:42