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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4093 - (hide annotations) (download) (as text)
Mon Feb 12 12:26:06 2024 UTC (2 months, 1 week ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 16295 byte(s)
* Move system dependent type and macro definitions into a shared header
  file sysdef.h (fixes compilation error with MSVC).

* Bumped version (4.4.0.svn2).

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

  ViewVC Help
Powered by ViewVC