/[svn]/libgig/trunk/src/helper.h
ViewVC logotype

Contents of /libgig/trunk/src/helper.h

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3730 - (show annotations) (download) (as text)
Sat Feb 1 12:06:25 2020 UTC (2 years, 10 months ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 16391 byte(s)
Added 2 new helper functions for potential future use:

- Added helper function store64().

- Added helper function binToHexStr().

1 /***************************************************************************
2 * *
3 * libgig - C++ cross-platform Gigasampler format file access library *
4 * *
5 * Copyright (C) 2003-2020 by Christian Schoenebeck *
6 * <cuse@users.sourceforge.net> *
7 * *
8 * This library is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this library; if not, write to the Free Software *
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21 * MA 02111-1307 USA *
22 ***************************************************************************/
23
24 #ifndef __LIBGIG_HELPER_H__
25 #define __LIBGIG_HELPER_H__
26
27 #include <string.h>
28 #include <string>
29 #include <sstream>
30 #include <algorithm>
31
32 #if defined(WIN32) && !HAVE_CONFIG_H && !defined(_MSC_VER)
33 # include "../win32/libgig_private.h" // like config.h, automatically generated by Dev-C++
34 # define PACKAGE "libgig"
35 # define VERSION VER_STRING // VER_STRING defined in libgig_private.h
36 #endif // WIN32
37
38 #if (HAVE_CONFIG_H /*&& !HAVE_VASPRINTF*/ && defined(WIN32)) || defined(_MSC_VER)
39 # include <stdarg.h>
40 int vasprintf(char** ret, const char* format, va_list arg);
41 #endif
42
43 #if defined(_MSC_VER)
44 # if _MSC_VER < 1900
45 # error versions prior to msvc 2015 have not been tested
46 # else
47 # include <BaseTsd.h>
48 typedef SSIZE_T ssize_t;
49 # endif
50 #endif
51
52 #include "RIFF.h"
53
54 // *************** Helper Functions **************
55 // *
56
57 template<class T> inline std::string ToString(T o) {
58 std::stringstream ss;
59 ss << o;
60 return ss.str();
61 }
62
63 // Behaves as printf() just that it returns it as string instead of writing to stdout.
64 inline std::string strPrint(const char* fmt, ...) {
65 va_list args;
66 va_start(args, fmt);
67 char* buf = NULL;
68 vasprintf(&buf, fmt, args);
69 std::string res = buf;
70 if (buf) free(buf);
71 va_end(args);
72 return res;
73 }
74
75 inline std::string toLowerCase(std::string s) {
76 std::transform(s.begin(), s.end(), s.begin(), ::tolower);
77 return s;
78 }
79
80 inline long Min(long A, long B) {
81 return (A > B) ? B : A;
82 }
83
84 inline long Abs(long val) {
85 return (val > 0) ? val : -val;
86 }
87
88 inline void swapBytes_16(void* Word) {
89 uint8_t byteCache = *((uint8_t*) Word);
90 *((uint8_t*) Word) = *((uint8_t*) Word + 1);
91 *((uint8_t*) Word + 1) = byteCache;
92 }
93
94 inline void swapBytes_32(void* Word) {
95 uint8_t byteCache = *((uint8_t*) Word);
96 *((uint8_t*) Word) = *((uint8_t*) Word + 3);
97 *((uint8_t*) Word + 3) = byteCache;
98 byteCache = *((uint8_t*) Word + 1);
99 *((uint8_t*) Word + 1) = *((uint8_t*) Word + 2);
100 *((uint8_t*) Word + 2) = byteCache;
101 }
102
103 inline void swapBytes_64(void* Word) {
104 uint8_t byteCache = ((uint8_t*)Word)[0];
105 ((uint8_t*)Word)[0] = ((uint8_t*)Word)[7];
106 ((uint8_t*)Word)[7] = byteCache;
107 byteCache = ((uint8_t*)Word)[1];
108 ((uint8_t*)Word)[1] = ((uint8_t*)Word)[6];
109 ((uint8_t*)Word)[6] = byteCache;
110 byteCache = ((uint8_t*)Word)[2];
111 ((uint8_t*)Word)[2] = ((uint8_t*)Word)[5];
112 ((uint8_t*)Word)[5] = byteCache;
113 byteCache = ((uint8_t*)Word)[3];
114 ((uint8_t*)Word)[3] = ((uint8_t*)Word)[4];
115 ((uint8_t*)Word)[4] = byteCache;
116 }
117
118 inline void swapBytes(void* Word, uint64_t WordSize) {
119 uint8_t byteCache;
120 uint64_t lo = 0, hi = WordSize - 1;
121 for (; lo < hi; hi--, lo++) {
122 byteCache = *((uint8_t*) Word + lo);
123 *((uint8_t*) Word + lo) = *((uint8_t*) Word + hi);
124 *((uint8_t*) Word + hi) = byteCache;
125 }
126 }
127
128 /**
129 * Stores a 16 bit integer in memory using little-endian format.
130 *
131 * @param pData - memory pointer
132 * @param data - integer to be stored
133 */
134 inline void store16(uint8_t* pData, uint16_t data) {
135 pData[0] = data;
136 pData[1] = data >> 8;
137 }
138
139 /**
140 * Stores a 32 bit integer in memory using little-endian format.
141 *
142 * @param pData - memory pointer
143 * @param data - integer to be stored
144 */
145 inline void store32(uint8_t* pData, uint32_t data) {
146 pData[0] = data;
147 pData[1] = data >> 8;
148 pData[2] = data >> 16;
149 pData[3] = data >> 24;
150 }
151
152 /**
153 * Stores a 64 bit integer in memory using little-endian format.
154 *
155 * @param pData - memory pointer
156 * @param data - integer to be stored
157 */
158 inline void store64(uint8_t* pData, uint64_t data) {
159 pData[0] = data;
160 pData[1] = data >> 8;
161 pData[2] = data >> 16;
162 pData[3] = data >> 24;
163 pData[4] = data >> 32;
164 pData[5] = data >> 40;
165 pData[6] = data >> 48;
166 pData[7] = data >> 56;
167 }
168
169 /**
170 * Loads a 16 bit integer in memory using little-endian format.
171 *
172 * @param pData - memory pointer
173 * @returns 16 bit data word
174 */
175 inline uint16_t load16(uint8_t* pData) {
176 return uint16_t(pData[0]) |
177 uint16_t(pData[1]) << 8;
178 }
179
180 /**
181 * Loads a 32 bit integer in memory using little-endian format.
182 *
183 * @param pData - memory pointer
184 * @returns 32 bit data word
185 */
186 inline uint32_t load32(uint8_t* pData) {
187 return uint32_t(pData[0]) |
188 uint32_t(pData[1]) << 8 |
189 uint32_t(pData[2]) << 16 |
190 uint32_t(pData[3]) << 24;
191 }
192
193 /**
194 * Swaps the order of the data words in the given memory area
195 * with a granularity given by \a WordSize.
196 *
197 * @param pData - pointer to the memory area to be swapped
198 * @param AreaSize - size of the memory area to be swapped (in bytes)
199 * @param WordSize - size of the data words (in bytes)
200 */
201 inline void SwapMemoryArea(void* pData, unsigned long AreaSize, uint WordSize) {
202 if (!AreaSize) return; // AreaSize==0 would cause a segfault here
203 switch (WordSize) { // TODO: unefficient
204 case 1: {
205 uint8_t* pDst = (uint8_t*) pData;
206 uint8_t cache;
207 unsigned long lo = 0, hi = AreaSize - 1;
208 for (; lo < hi; hi--, lo++) {
209 cache = pDst[lo];
210 pDst[lo] = pDst[hi];
211 pDst[hi] = cache;
212 }
213 break;
214 }
215 case 2: {
216 uint16_t* pDst = (uint16_t*) pData;
217 uint16_t cache;
218 unsigned long lo = 0, hi = (AreaSize >> 1) - 1;
219 for (; lo < hi; hi--, lo++) {
220 cache = pDst[lo];
221 pDst[lo] = pDst[hi];
222 pDst[hi] = cache;
223 }
224 break;
225 }
226 case 4: {
227 uint32_t* pDst = (uint32_t*) pData;
228 uint32_t cache;
229 unsigned long lo = 0, hi = (AreaSize >> 2) - 1;
230 for (; lo < hi; hi--, lo++) {
231 cache = pDst[lo];
232 pDst[lo] = pDst[hi];
233 pDst[hi] = cache;
234 }
235 break;
236 }
237 default: {
238 uint8_t* pCache = new uint8_t[WordSize]; // TODO: unefficient
239 unsigned long lo = 0, hi = AreaSize - WordSize;
240 for (; lo < hi; hi -= WordSize, lo += WordSize) {
241 memcpy(pCache, (uint8_t*) pData + lo, WordSize);
242 memcpy((uint8_t*) pData + lo, (uint8_t*) pData + hi, WordSize);
243 memcpy((uint8_t*) pData + hi, pCache, WordSize);
244 }
245 if (pCache) delete[] pCache;
246 break;
247 }
248 }
249 }
250
251 /** @brief Load given info field (string).
252 *
253 * Load info field string from given info chunk (\a ck) and save value to \a s.
254 */
255 inline void LoadString(RIFF::Chunk* ck, std::string& s) {
256 if (ck) {
257 const char* str = (char*)ck->LoadChunkData();
258 if (!str) {
259 ck->ReleaseChunkData();
260 s = "";
261 return;
262 }
263 int size = (int) ck->GetSize();
264 int len;
265 for (len = 0 ; len < size ; len++)
266 if (str[len] == '\0') break;
267 s.assign(str, len);
268 ck->ReleaseChunkData();
269 }
270 }
271
272 /** @brief Apply given INFO field to the respective chunk.
273 *
274 * Apply given info value string to given info chunk, which is a
275 * subchunk of INFO list chunk \a lstINFO. If the given chunk already
276 * exists, value \a s will be applied. Otherwise if it doesn't exist yet
277 * and either \a s or \a sDefault is not an empty string, such a chunk
278 * will be created and either \a s or \a sDefault will be applied
279 * (depending on which one is not an empty string, if both are not an
280 * empty string \a s will be preferred).
281 *
282 * @param ChunkID - 32 bit RIFF chunk ID of INFO subchunk (only used in case \a ck is NULL)
283 * @param ck - INFO (sub)chunk where string should be stored to
284 * @param lstINFO - parent (INFO) RIFF list chunk
285 * @param s - current value of info field
286 * @param sDefault - default value
287 * @param bUseFixedLengthStrings - should a specific string size be forced in the chunk?
288 * @param size - wanted size of the INFO chunk. This is ignored if bUseFixedLengthStrings is false.
289 */
290 inline void SaveString(uint32_t ChunkID, RIFF::Chunk* ck, RIFF::List* lstINFO, const std::string& s, const std::string& sDefault, bool bUseFixedLengthStrings, int size) {
291 if (ck) { // if chunk exists already, use 's' as value
292 if (!bUseFixedLengthStrings) size = (int) s.size() + 1;
293 ck->Resize(size);
294 char* pData = (char*) ck->LoadChunkData();
295 strncpy(pData, s.c_str(), size);
296 } else if (s != "" || sDefault != "" || bUseFixedLengthStrings) { // create chunk
297 const std::string& sToSave = (s != "") ? s : sDefault;
298 if (!bUseFixedLengthStrings) size = (int) sToSave.size() + 1;
299 ck = lstINFO->AddSubChunk(ChunkID, size);
300 char* pData = (char*) ck->LoadChunkData();
301 strncpy(pData, sToSave.c_str(), size);
302 }
303 }
304
305 // private helper function to convert progress of a subprocess into the global progress
306 inline void __notify_progress(RIFF::progress_t* pProgress, float subprogress) {
307 if (pProgress && pProgress->callback) {
308 const float totalrange = pProgress->__range_max - pProgress->__range_min;
309 const float totalprogress = pProgress->__range_min + subprogress * totalrange;
310 pProgress->factor = totalprogress;
311 pProgress->callback(pProgress); // now actually notify about the progress
312 }
313 }
314
315 // private helper function to divide a progress into subprogresses
316 inline void __divide_progress(RIFF::progress_t* pParentProgress, RIFF::progress_t* pSubProgress, float totalTasks, float currentTask) {
317 if (pParentProgress && pParentProgress->callback) {
318 const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min;
319 pSubProgress->callback = pParentProgress->callback;
320 pSubProgress->custom = pParentProgress->custom;
321 pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
322 pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
323 }
324 }
325
326 // private helper function to divide a progress into subprogresses
327 inline void __divide_progress(RIFF::progress_t* pParentProgress, RIFF::progress_t* pSubProgress, float total, float lo, float hi) {
328 if (pParentProgress && pParentProgress->callback) {
329 const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min;
330 pSubProgress->callback = pParentProgress->callback;
331 pSubProgress->custom = pParentProgress->custom;
332 pSubProgress->__range_min = pParentProgress->__range_min + totalrange * (lo / total);
333 pSubProgress->__range_max = pSubProgress->__range_min + totalrange * ((hi-lo) / total);
334 }
335 }
336
337
338 /*****************************************************************************
339 * Any problems with any of the following helper functions? *
340 * *
341 * Then please first have a look at their current TEST CASES at *
342 * src/testcases/HelperTest.cpp as basis for your modifications! *
343 *****************************************************************************/
344
345
346 /// Removes one or more consecutive occurences of @a needle from the end of @a haystack.
347 inline std::string strip2ndFromEndOf1st(const std::string haystack, char needle) {
348 if (haystack.empty()) return haystack;
349 if (*haystack.rbegin() != needle) return haystack;
350 for (int i = haystack.length() - 1; i >= 0; --i)
351 if (haystack[i] != needle)
352 return haystack.substr(0, i+1);
353 return "";
354 }
355
356 #ifndef NATIVE_PATH_SEPARATOR
357 # ifdef _WIN32
358 # define NATIVE_PATH_SEPARATOR '\\'
359 # else
360 # define NATIVE_PATH_SEPARATOR '/'
361 # endif
362 #endif
363
364 /**
365 * Returns the owning path of the given path (its parent path). So for example
366 * passing "/some/path" would return "/some".
367 */
368 inline std::string parentPath(const std::string path) {
369 if (path.empty()) return path;
370 std::string s = strip2ndFromEndOf1st(path, NATIVE_PATH_SEPARATOR);
371 if (s.empty()) {
372 s.push_back(NATIVE_PATH_SEPARATOR); // i.e. return "/"
373 return s;
374 }
375 #if defined(_WIN32)
376 if (s.length() == 2 && s[1] == ':')
377 return s;
378 #endif
379 std::size_t pos = s.find_last_of(NATIVE_PATH_SEPARATOR);
380 if (pos == std::string::npos) return "";
381 if (pos == 0) {
382 s = "";
383 s.push_back(NATIVE_PATH_SEPARATOR); // i.e. return "/"
384 return s;
385 }
386 return s.substr(0, pos);
387 }
388
389 /**
390 * Returns the last (lowest) portion of the given path. So for example passing
391 * "/some/path" would return "path".
392 */
393 inline std::string lastPathComponent(const std::string path) {
394 #if defined(_WIN32)
395 if (path.length() == 2 && path[1] == ':')
396 return "";
397 #endif
398 std::size_t pos = path.find_last_of(NATIVE_PATH_SEPARATOR);
399 return (pos == std::string::npos) ? path : path.substr(pos+1);
400 }
401
402 /**
403 * Returns the given path with the type extension being stripped from its end.
404 * So for example passing "/some/path.foo" would return "/some/path".
405 */
406 inline std::string pathWithoutExtension(const std::string path) {
407 std::size_t posSep = path.find_last_of(NATIVE_PATH_SEPARATOR);
408 std::size_t posBase = (posSep == std::string::npos) ? 0 : posSep+1;
409 std::size_t posDot = path.find_last_of(".");
410 return (posDot != std::string::npos && posDot > posBase)
411 ? path.substr(0, posDot) : path;
412 }
413
414 /**
415 * Returns the type extension of the given path. So for example passing
416 * "/some/path.foo" would return "foo".
417 */
418 inline std::string extensionOfPath(const std::string path) {
419 std::size_t posSep = path.find_last_of(NATIVE_PATH_SEPARATOR);
420 std::size_t posBase = (posSep == std::string::npos) ? 0 : posSep+1;
421 std::size_t posDot = path.find_last_of(".");
422 return (posDot != std::string::npos && posDot > posBase)
423 ? path.substr(posDot+1) : "";
424 }
425
426 /**
427 * Combines the two given paths with each other. So for example passing
428 * "/some/path" and "/another/one" would return "/some/path/another/one".
429 */
430 inline std::string concatPath(const std::string path1, const std::string path2) {
431 return (!path1.empty() && *(path1.rbegin()) != NATIVE_PATH_SEPARATOR &&
432 !path2.empty() && *(path2.begin()) != NATIVE_PATH_SEPARATOR)
433 ? path1 + NATIVE_PATH_SEPARATOR + path2
434 : path1 + path2;
435 }
436
437 /**
438 * Returns a hex string representation of the binary data being passed.
439 */
440 inline std::string binToHexStr(const void* pData, size_t sz) {
441 std::string s;
442 for (size_t i = 0; i < sz; ++i) {
443 s += strPrint("%02x", ((const char*)pData)[i]);
444 }
445 return s;
446 }
447
448 #endif // __LIBGIG_HELPER_H__

  ViewVC Help
Powered by ViewVC