Essentia  2.1-beta6-dev
betools.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
3  *
4  * This file is part of Essentia
5  *
6  * Essentia is free software: you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License as published by the Free
8  * Software Foundation (FSF), either version 3 of the License, or (at your
9  * option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the Affero GNU General Public License
17  * version 3 along with this program. If not, see http://www.gnu.org/licenses/
18  */
19 
20 #ifndef BETOOLS_H
21 #define BETOOLS_H
22 
23 #include <algorithm>
24 #include <fstream>
25 #include <cassert>
26 #include "types.h"
27 
28 // This file contains serialization helper functions that should be aware of
29 // endianness: they assume all streams are big-endian (network-order),
30 // regardless of the architecture
31 
32 namespace essentia {
33 
34 inline bool isBigEndian() {
35  const int i = 1;
36  return (*(char*)&i) == 0;
37 }
38 
39 template <typename T>
40 void removeEndianness(T& x) {
41  if (isBigEndian()) return;
42  char* p = (char*)&x;
43  std::reverse(p, p+sizeof(T));
44 }
45 
46 
47 
48 template <typename T>
49 void bewrite(std::ofstream& out, const T& value) {
50  T becopy(value);
51  removeEndianness(becopy);
52  out.write((char*)&becopy, sizeof(becopy));
53 }
54 
55 template <>
56 void bewrite(std::ofstream& out, const std::string& str) {
57  bewrite(out, (sint32)str.size());
58  out.write(str.c_str(), (int)str.size());
59 }
60 
61 template <>
62 void bewrite(std::ofstream& out, const std::vector<std::string>& v) {
63  sint32 size = (sint32)v.size();
64  bewrite(out, size);
65  for (int i=0; i<size; i++) bewrite(out, v[i]);
66 }
67 
68 
69 
70 template <typename T>
71 void beread(std::ifstream& in, T& value) {
72  in.read((char*)&value, sizeof(value));
73  removeEndianness(value);
74 }
75 
76 template <>
77 void beread(std::ifstream& in, std::string& str) {
78  sint32 size;
79  beread(in, size);
80  str.resize(size);
81  in.read(&str[0], size);
82 }
83 
84 template <>
85 void beread(std::ifstream& in, std::vector<std::string>& v) {
86  sint32 size;
87  beread(in, size);
88  v.resize(size);
89  for (int i=0; i<size; i++) beread(in, v[i]);
90 }
91 
92 } // namespace essentia
93 
94 #endif // BETOOLS_H
Definition: algorithm.h:28
void beread(std::ifstream &in, T &value)
Definition: betools.h:71
void removeEndianness(T &x)
Definition: betools.h:40
void bewrite(std::ofstream &out, const T &value)
Definition: betools.h:49
bool isBigEndian()
Definition: betools.h:34
int32_t sint32
Definition: types.h:46